编写一个程序实现顺序栈(假设栈中元素类型为char)的各种基本运算,并在此基础上设计一个主程序完成如下功能:
(1)初始化顺序栈S;
(2)判断顺序栈S是否为空;
(3)依次进栈元素a,b,c,d,e;
(4)判断顺序栈S是否为空;
(5)输出顺序栈长度;
(6)输出从栈顶到栈底的元素;
(7)输出出栈序列;
(8)判断顺序栈S是否为空;
(9)释放顺序栈。
输入
两行数据,第一行是入栈字符数据的个数,第二行是具体入栈的字符数据。
输出
按照程序要求输出。
样例输入
5
a b c d e
样例输出
yes
no
5
e d c b a
e d c b a
yes
代码实现:
#include<iostream> using namespace std; typedef char ElemType; typedef struct{ ElemType *data; int top; }Sqstack; void init(Sqstack &s,int n){ s.data = new ElemType[n]; s.top = -1; } bool empty(Sqstack s){ return s.top == -1; } void push(Sqstack &s,ElemType e){ s.data[++s.top] = e; } void display(Sqstack s){ for(int i=s.top;i>=0;i--){ cout<<s.data[i]<<" "; } cout<<endl; } void pop(Sqstack &s){ if(empty(s)) return; s.top--; } ElemType top(Sqstack s){ return s.data[s.top]; } int size(Sqstack s){ return s.top+1; } void destroy(Sqstack &s){ delete []s.data; } int main(void){ Sqstack s; int n; cin>>n; init(s,n); if(empty(s)) cout<<"yes"<<endl; else cout<<"no"<<endl; for(int i=0;i<n;i++){ ElemType e; cin>>e; push(s,e); } if(empty(s)) cout<<"yes"<<endl; else cout<<"no"<<endl; cout<<size(s)<<endl; display(s); while(!empty(s)){ cout<<top(s)<<" "; pop(s); } cout<<endl; if(empty(s)) cout<<"yes"<<endl; else cout<<"no"<<endl; destroy(s); return 0; }