#include<iostream>
using namespace std;
#define Maxsize 50
typedef struct{
int data[Maxsize];
int top;
}SqStack;
void InitStack(SqStack &S){
S.top=-1;//初始化栈顶指针
}
bool StackEmpty(SqStack S){
if(S.top==-1)
return true;//栈空
else
return false;//不空
}
bool Push(SqStack &S,int x){
if(S.top==Maxsize-1)//栈满,报错
return false;
S.data[++S.top]=x;//指针先加1,再入栈
return true;
}
bool Pop(SqStack &S,int &x){
if(S.top==-1)
return false;
x=S.data[S.top--];//先出栈,指针再减一
return true;
}
bool GetTop(SqStack S,int &x){
if(S.top==-1)//栈空,报错
return false;
x=S.data[S.top];//x记录栈顶元素
return true;
}
int main(){
SqStack S;
InitStack(S);
cout<<"初始化结束"<<endl;
if(StackEmpty(S))
cout<<"栈空"<<endl;
else
cout<<"不空"<<endl;
cout<<"请输入入栈个数:"<<endl;
int n;
cin>>n;
cout<<"请依次输入入栈元素:"<<endl;
for(int i=0;i<n;i++){
int num;
cin>>num;
Push(S,num);
}
if(!StackEmpty(S)){
int top;
GetTop(S,top);
cout<<"TOP 是:"<<top<<endl;
}
int pop;
Pop(S,pop);
cout<<"出栈元素:"<<pop<<endl;
if(StackEmpty(S))
cout<<"栈空"<<endl;
else{
cout<<"不空"<<endl;
int top;
GetTop(S,top);
cout<<"此时TOP 是:"<<top<<endl;
}
return 0;
}
【数据结构】顺序栈
猜你喜欢
转载自blog.csdn.net/weixin_38220799/article/details/106572235
今日推荐
周排行