顺序栈
来源:互联网 发布:没有网络连接 编辑:程序博客网 时间:2024/05/17 04:01
/*实验22. 完成对顺序栈结构的定义,以及对顺序栈的各种基本运算的实现(每种基本运算用一个函数来实现)。基本运算包括:初始化Init_sqstack运算、判栈空Empty_sqstack运算、入栈Push_sqstack运算、出栈Pop_sqstack运算、取栈顶元素Gettop_sqstack运算。并且在main函数中分别调用以上各种基本运算的函数来使用,以证明其功能已实现。此题的源程序保存为 3_a1.cpp。*/#include<iostream>using namespace std;typedef char datatype; //栈元素类型,假设为整型const int maxsize=100; //栈容量typedef struct { datatype data[maxsize]; int top;} sqstack;//顺序栈类型sqstack* Init_sqstack( ) { sqstack *sq = new sqstack; sq->top=-1; return sq;}int Empty_sqstack(sqstack *sq) {if(sq->top==-1) return 1;else return 0;}int Push_sqstack(sqstack *sq,datatype x) {if(sq->top==maxsize-1)//上溢 {cout<<"栈满,不能入栈!\n";return 0;} else {++sq->top;sq->data[sq->top]=x; return 1;}}int Pop_sqstack(sqstack *sq,datatype &x){if(sq->top==-1)//下溢 {cout<<"栈空,不能出栈!\n"; return 0;}else {x = sq->data[sq->top]; sq->top--;return 1;}}int Gettop_sqstack(sqstack *sq,datatype &x) {if(sq->top==-1) {cout<<"栈空,无栈顶可取!\n"; return 0;}else {x = sq->data[sq->top];return 1;}}void Display(sqstack *sq){int i;if(Empty_sqstack(sq)){cout<<"此时栈为空。"<<endl;}else{cout<<"栈底到栈顶的元素依次是:";for(i=0 ; i<=sq->top ;i++)cout<<sq->data[i]<<" ";cout<<endl;}}int main(){sqstack *S;S=Init_sqstack();char choice,x;int flag = 1;while(flag){cout<<"------------顺序栈------------------------------"<<endl;cout<<" 1. 入栈 "<<endl;cout<<" 2. 出栈 "<<endl;cout<<" 3. 取栈顶元素 "<<endl;cout<<" 4. 判断栈是否为空 "<<endl;cout<<" 5. 浏览栈底到栈顶所有元素(测试用) "<<endl;cout<<" 6. 退出 "<<endl;cout<<"------------------------------------------------"<<endl;cout<<"请选择:";cin>>choice;switch(choice){case '1':cout<<"请输入一个需要入栈的字符"<<endl;cin>>x;if(Push_sqstack(S,x))cout<<"入栈成功"<<endl;elsecout<<"入栈失败!"<<endl;break;case '2': if(Pop_sqstack(S,x))cout<<"出栈成功,弹出栈的元素是:"<<x<<endl;elsecout<<"出栈失败!"<<endl;break;case '3':if(Gettop_sqstack(S,x))cout<<"取栈顶元素成功,弹出栈的元素是:"<<x<<endl;elsecout<<"取栈顶元素失败!"<<endl;break;case '4': if(Empty_sqstack(S))cout<<"此时栈为空。"<<x<<endl;elsecout<<"此时栈不为空。"<<endl;break;case '5': Display(S);break;case '6': flag=0; break;default : cout<<"输入错误,请重新选择。"<<endl;}}return 0;}