Code
/*
InitStack(&S):初始化一个空栈S。
StackEmpty(S):判断一个栈是否为空,若栈为空则返回true,否则返回false。
Push(&S, x):进栈,若栈S未满,则将x加入使之成为新栈顶。
Pop(&S, &x):出栈,若栈非空,则弹出栈顶元素,并用x返回。
GetTop(S, &x):读栈顶元素,若栈非空则用x返回栈顶元素。
ClearStack(&S):销毁栈,并释放S占用的内存空间。
* */
#include <iostream>
using namespace std;
#define MaxSize 50
#define ElemType int
typedef struct {
ElemType data[MaxSize]={0};
int top;//栈顶“指针” 就指向栈顶元素,不是栈顶元素的下一位空白区域
}SqStack;
/*
从下标为0开始存储
栈空条件:S.top == -1
栈长:S.top+1
栈满条件:S.top == MaxSize-1
* */
//初始化
void InitStack(SqStack &S){
//要做的工作就是将栈空;
S.top=-1;
}
//判断栈空
bool StackEmpty(SqStack S){
if(S.top == -1)
return true;
else
return false;
}
//进栈
bool Push(SqStack &S,ElemType x){
if(S.top==MaxSize-1)//如果栈满,返回false
return false;
S.data[++S.top]=x;
return true;
}
//出栈
bool Pop(SqStack &S, ElemType x){
if(S.top==-1)//栈空,无法出
return false;
x=S.data[S.top];
S.top--;
return true;
}
//打印
void show(SqStack S){
for(int i=0;i<=S.top;i++){
cout<<S.data[i]<<" ";
}
}
//读取栈顶元素,用x接受
ElemType GetTop(SqStack S, ElemType &x){
if(S.top==-1)
return -1;
x=S.data[S.top];
return x;
}
//销毁栈,并释放S占用的内存空间
void ClearStack(SqStack &S){
//顺序栈不用释放空间。
}
int main(){
SqStack S;
InitStack(S);
cout<<S.top<<endl;
Push(S,3);
Push(S,6);
Push(S,11);
show(S);
return 0;
}
Input && Output
-1
3 6 11
Process finished with exit code 0