顺序栈的实现

顺序栈是一种基于数组实现的栈,它的特点是后进先出(LIFO)。在顺序栈中,所有的栈操作都是在栈顶进行的,栈顶元素是最后一个入栈的元素。

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
typedef int SElemType;
typedef int Status;
#define OVERFLOW -1
#define ERROR 0
#define OK 1
#define MAXSIZE 100
typedef struct {
    SElemType* base;
    SElemType* top;
    int stacksize;
}SqStack;
SqStack S;
//顺序栈初始化
Status InitStack(SqStack& S) {//构造一个空栈
    //S.base=new SElemType[MAXSIZE];
    S.base = (SElemType*)malloc(sizeof(SElemType) * MAXSIZE);
    if (!S.base) exit(OVERFLOW);//分配失败
    S.top = S.base;//栈顶指针等于栈底指针
    S.stacksize = MAXSIZE;
}
//判断顺序栈是否为空
Status StackEmpty(SqStack S) {
    //判断栈为空,返回OK;否则返回ERROR
    if (S.base == S.top)
        return OK;
    else
        return ERROR;
}
//求顺序栈的长度
int StackLenght(SqStack S) {
    return S.top - S.base;
}
//清空顺序栈
Status ClearStack(SqStack S) {
    if (S.base)
        S.top = S.base;
    return OK;
}
//销毁顺序栈
Status DestroyStack(SqStack& S) {
    if (S.base) {
        free(S.base);
        S.stacksize = 0;
        S.base = S.top = NULL;
    }
    return OK;
}
//判断栈满
Status isFULL(SqStack S) {
    if (S.top - S.base >= S.stacksize)
        return OK;
    return ERROR;
}
//顺序栈的入栈
Status Push(SqStack& S, SElemType e) {
    if (isFULL(S))
        return ERROR;
    *S.top++ = e;
    return OK;
}
//顺序栈出栈
Status Pop(SqStack& S, SElemType& e) {
    if (!StackEmpty(S)) {
        e = *(--S.top);
        return OK;
    }
    return ERROR;
}
int main()
{
    InitStack(S);
    SElemType e;
    scanf("%d", &e);
    while (e != -1)    //入栈 输入1 2 3 4    -1 终止循环
    {
        Push(S, e);
        scanf("%d", &e);
    }
    int len = StackLenght(S);  //长度   4
    printf("%d\n", len);
    while (!StackEmpty(S)) {  //出栈 输出4321
        Pop(S, e);
        printf("%d", e);
    }
}