#include <cstdio>
#define MaxSize 50
typedef struct{
int data[MaxSize];
int top;
}SqStack;
void InitStack(SqStack &S){
S.top = -1;
}
bool StackEmpty(SqStack S){
return(S.top==-1);
}
bool Push(SqStack &S,int x){
if(S.top==MaxSize-1){
printf("该栈已满!");
return false;
}
S.data[++S.top] = x;
return true;
}
bool Pop(SqStack &S,int &x){
if(S.top==-1){
printf("该栈为空!");
return false;
}
x = S.data[S.top--];
return true;
}
bool GetTop(SqStack S,int &x){
if(S.top==-1){
printf("该栈为空!");
return false;
}
x = S.data[S.top];
return true;
}
//用于测试
void Print(SqStack S){
int len = S.top+1;
for(int i=0;i<len;i++){
printf("%d ",S.data[i]);
}
printf("\n");
}
int main(){
int x;
SqStack S;
InitStack(S);
Push(S,1);
Push(S,2);
Push(S,1);
Push(S,3);
Print(S);
GetTop(S,x);
printf("栈顶元素为:%d\n",x);
Pop(S,x);
Print(S);
return 0;
}
顺序栈(C++)
于 2023-11-16 18:35:00 首次发布