#include <iostream>
#include <cstdlib>
using namespace std;
#define MAXSIZE 50
//数据类型
struct ElemType{
int n;
};
//栈结点结构体
typedef struct{
ElemType data[MAXSIZE];
int top;//栈顶
}SqStack;
class Sq_Stack{
public:
//初始化
Sq_Stack(){
cout<<"初始化栈"<<endl;
S.top = -1; //初始化栈顶为-1
}
//判断栈空
bool IsEmpty(){
if(S.top==-1)
return true;
else
return false;
}
//进栈
bool Push(ElemType e){
//判断是否栈满
if(S.top==MAXSIZE-1)
return false;
//插入元素
S.data[++S.top]=e;
return true;
}
//出栈
bool Pop(ElemType &e){
//判断是否为栈空
if(S.top==-1)
return false;
//取栈顶
e=S.data[S.top--];
return true;
}
//读取栈顶元素
bool GetTop(ElemType &e){
//判断是否为栈空
if(S.top==-1)
return false;
//取栈顶
e=S.data[S.top];
return true;
}
//输出栈的元素
void Show(){
for(int i=S.top;i>=0;i--){
cout<<" |"<<S.data[i].n<<"|"<<endl;
}
cout<<endl;
}
//功能选择
void Choice(int c){
ElemType e;
switch(c){
case 1:
cout<<"请输入元素的值"<<endl;
cin>>e.n;
Push(e);
break;
case 2:
cout<<"出栈"<<endl;
Pop(e);
cout<<"出栈元素为"<<e.n<<endl;
break;
case 3:
cout<<"读取栈顶元素"<<endl;
GetTop(e);
cout<<"栈顶元素为"<<e.n<<endl;
break;
case 4:
if(IsEmpty()){
cout<<"栈空"<<endl;
}
else{
cout<<"栈非空"<<endl;
}
break;
case 0:
cout<<"退出程序";
exit(0);
default:
cout<<"输出格式错误"<<endl;
break;
}
Show();
}
private:
SqStack S;
};
void Welcome(){
cout<<"======功能选择======"<<endl;
cout<<"1->入栈"<<endl;
cout<<"2->出栈"<<endl;
cout<<"3->读取栈顶元素"<<endl;
cout<<"4->判断栈是否空"<<endl;
cout<<"0->退出程序"<<endl;
}
int main()
{
Sq_Stack s;
Welcome();
int c;
while(true){
cout<<"请输入操作"<<endl<<">>";
cin>>c;
s.Choice(c);
}
return 0;
}