#include<stdio.h>
#define MaxSize 20
typedef struct SqueueStack {
int data[MaxSize];
int top;
} SqStack;
//初始化栈
void initSqStack(SqStack &S) {
S.top=-1;
}
//判断栈空
bool StackEmpty(SqStack S) {
if(S.top==-1) {
return true;
} else {
return false;
}
}
//入栈 push
bool Push(SqStack &S,int x) {
if(S.top == MaxSize-1) {
return false;
}
S.top =S.top+1;
S.data[S.top]=x;
return true;
}
//出栈 pop
bool Pop(SqStack &S,int &e) {
if(StackEmpty(S)) {
printf("栈为空");
return false;
}
e=S.data[S.top];
S.top=S.top-1;
return true;
}
//获取栈顶元素 GetTop
int GetEle(SqStack S) {
if(StackEmpty(S)) {
printf("栈为空");
return 0;
}
int x=S.data[S.top];
return x;
}
//销毁栈 DestroyStack
bool DestoryStack(SqStack &S){
for(int i=0;i<S.top;i++){
S.data[i]=0;
}
S.top=-1;
return true;
}
//栈的长度
int Length(SqStack S){
int length = S.top;
return length;
}
//打印栈
void PrintStack(SqStack S) {
if(StackEmpty(S)){
printf("栈为空!");
return ;
}
printf("从栈顶元素开始,栈如下:\n");
while (S.top > 0) {//注意判空的条件
printf("S[%d]=%d\n", S.top, S.data[S.top--]);
}
printf("栈打印完毕\n");
}
int main() {
SqStack S;
initSqStack(S);
for(int i=0;i<11;i++){
Push(S,i);
}
int length = Length(S);
printf("顺序栈的长度为%d\n",length);
PrintStack(S);
printf("\n\n");
printf("当前栈顶元素为:%d", GetEle(S));
printf("\n\n");
int e=0;
Pop(S,e);
printf("出栈元素为:%d",e);
printf("\n\n");
printf("当前栈顶元素为:%d", GetEle(S));
PrintStack(S);
printf("\n\n");
DestoryStack(S);
printf("栈销毁之后:\n");
PrintStack(S);
printf("\n\n");
return 0;
}
顺序栈
最新推荐文章于 2024-09-14 15:29:46 发布