本文实现王道书上的对于顺序栈的基本操作,代码与书本略有不同。链栈只是为了让共享栈的效率更高,而链栈只允许在表头操作,这跟单链表的头插法一毛一样
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MaxSize 10
typedef struct {
int data[MaxSize];
int top;
}SqStack;
//初始化栈
SqStack InitSqStack(SqStack S){
S.top = -1;
printf("顺序栈的初始化成功!\n");
return S;
}
//判断栈是否为空
void EmptyStack(SqStack S){
if(S.top==-1){
printf("该栈为空!\n");
}else{
printf("该栈非空!\n");
}
}
//进栈的操作
SqStack Push(SqStack S){
int x;
printf("请输入入栈元素:\n");
scanf("%d",&x);
if(S.top==MaxSize-1){
printf("顺序栈已满!\n");
}
while(x!=99){
S.data[++S.top]=x;
printf("请输入入栈元素:\n");
scanf("%d",&x);
}
return S;
}
//出栈,这里只出一个栈顶元素
int Pop(SqStack S){
int n;
if(S.top==-1){
printf("该栈为空,返回0 \n");
return 0;
}
n=S.data[S.top--];
return n;
}
//打印栈里面的所有元素
void PrintStack(SqStack S){
if(S.top==-1){
printf("这是一个空栈,输出错误!\n");
}
while(S.top>=0){
printf("%d ",S.data[S.top--]);
}
}
int main()
{
SqStack S;
SqStack s = InitSqStack(S);
s = Push(s);
EmptyStack(s);
printf("该顺序栈中的所有元素为:\n");
PrintStack(s);
printf("进行一个出栈操作,出栈的元素为:%d \n",Pop(s));
return 0;
}
运行结果: