数据结构——静态顺序栈的基本操作
代码主要来源:【数据结构】【清华大学】【严蔚敏】
/代码背景是基于书上的,可内容确实是自己理解后敲的,这不禁让人思考(纠结)原创的定义了/
顺序栈S的基本运算如下:
(1)初始化栈S
(2)栈为空
(3)依次进栈元素a,b,c,d,e
(4)栈为非空
(5)出栈序列:e d c b a
(6)栈为空
(7)释放栈
//本题静态栈,不用有释放空间的步骤,非要释放可以用memset(a,0,MAXSIZE)表示
//这个静态顺序栈(约等于是数组)可能是栈和队列类型中最简单的
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define TRUE 1
#define FALSE 0
#define MAXSIZE 100
typedef struct Stack {
char data[MAXSIZE]; // 栈
int top; // 栈顶指针(实际是数组的下标值)
} SqStack;
int InitStack(SqStack &S)
{
S.top=0;
}
int Push(SqStack &S,char e)
{
if(S.top>=MAXSIZE) return ERROR;
S.data[S.top++]=e;
return OK;
}
int Pop(SqStack &S,char &e)
{
if(S.top == 0) return ERROR;
e=S.data[--S.top];//e=*(S.data+S.top-1)
return OK;
}
int Empty(SqStack &S)
{
if(S.top == 0) return 1;
else return 0;
}
int main()
{
SqStack S;
char a[5]= {'a','b','c','d','e'},e;
InitStack(S);
if(Empty(S)) {
printf("栈为空\n");
}
for(int i=0; i<5; i++) {
Push(S,a[i]);
}
if(!Empty(S)) {
printf("栈非空\n");
}
while(!Empty(S)) {
Pop(S,e);
printf("%c ",e);
}
if(Empty(S)) {
printf("\n栈为空\n");
}
}