栈(stack)是一种比较基础的数据结构,其限制了删除和插入在一个位置操作,而其主要思想就是后进先出(LIFO)。

操作图示:

文章插图

具体细节可通过代码看出。

下面给出函数的声明部分:

StackRecord.h

#ifndef STACKRECORD_H
#define STACKRECORD_H

typedef char ElementType;
struct StackRecord;
typedef struct StackRecord *Stack;

int IsEmpty(Stack S);
int IsFull(Stack S);
Stack CreateStack(int MaxStackSize);
void DisposeStack(Stack S);
void MakeEmpty(Stack S);
void Push(Stack S, ElementType X);
void Pop(Stack S);
ElementType Top(Stack S);
ElementType PopAndTop(Stack S);

#endif

一般的,当我们创建一个栈时都会声明一个数组来储存元素,但是这是一个隐含的危险,一般数组大小都会有一个确定的值,而通常我们的程序往往潜在的存在多个栈。因此我们动态的申请一个数组,虽然贵这样花费了昂贵的malloc和free程序时间,但是这很符合我们ADT的想法!

栈的主要例程是Push()和Pop()两个例程:

StackFunction.c:

#include"StackRecord.h"
#include<stdio.h>
#include<stdlib.h>

#define EmptyStack -1/*默认空栈大小*/
#define MinStackSize 5

struct StackRecord{
    int Capacity;
    int TopOfStack;
    ElementType *Array;
};

int IsEmpty(Stack S)
{
    return S->TopOfStack == EmptyStack;
}

int IsFull(Stack S)
{
    return S->Capacity == S->TopOfStack + 1;/*加1因为数组的大小从0开始*/
}

Stack CreateStack(int MaxStackSize)
{
    Stack S;
    if(MaxStackSize < MinStackSize)
        printf("Stack is too small!");
    S = (Stack)malloc(sizeof(struct StackRecord));
    if(S == NULL)
        printf("malloc failure!");
    else{        /*Alloc a Arry size you wanted*/
        S->Array = (ElementType*)malloc(sizeof(ElementType) * MaxStackSize);
        if(S->Array == NULL)
            printf("malloc failure!");
        else{
            S->Capacity = MaxStackSize;
            MakeEmpty(S);
        }
    }
    return S;
}

void MakeEmpty(Stack S)
{
    S->TopOfStack = EmptyStack;
}

void DisposeStack(Stack S)
{
    if(S != NULL){//if S is NULL, that free(S) is meaningless
        free(S->Array);
        free(S);
    }
}

void Push(Stack S, ElementType X)
{
    if(IsFull(S))
        printf("Stack is full!");
    else
        S->Array[++S->TopOfStack] = X;
}

void Pop(Stack S)
{
    if(IsEmpty(S))
        printf("Stack is empty!");
    else
        S->TopOfStack--;
}

ElementType Top(Stack S)
{
    if(!IsEmpty(S))
        return S->Array[S->TopOfStack];
    printf("Stack is empty!");
    return 0;//return value used to avoid warning
}

ElementType PopAndTop(Stack S)
{
    if(!IsEmpty(S))
        return S->Array[S->TopOfStack--];
    printf("Stack is empty!");
    return 0;
}