- 初始化栈s;
- 判断栈s是否为空;
- 依次进栈元素a,b,c,d,e;
- 判断栈s是否为空;
- 输出出栈序列;
- 判断栈s是否为空;
- 释放栈。
#include<iostream> using namespace std; #define Maxsize 50 typedef char ElemType; typedef struct { ElemType data[Maxsize]; int top; }SqStack; //初始化栈 void InitStack(SqStack *&s) { s=(SqStack *)malloc(sizeof(SqStack)); s->top=-1; } //判断栈是否为空 bool StackEmpty(SqStack *s) { return(s->top==-1); } //依次进栈元素 bool Push(SqStack *&s,ElemType e) { if(s->top==Maxsize-1) return false; s->top++; s->data[s->top]=e; return true; } //输出出栈队列 bool Pop(SqStack *&s,ElemType &e) { if(s->top==-1) return false; e=s->data[s->top]; s->top--; return true; } //销毁栈 void DestoryStack(SqStack *&s) { free(s); } //主函数 int main() { char e; SqStack *s; cout<<"初始化栈"<<endl; InitStack(s); if(StackEmpty(s)==1) cout<<"栈为空"<<endl; else cout<<"栈不为空"<<endl; cout<<"依次进栈元素a,b,c,d,e"<<endl; Push(s,'a'); Push(s,'b'); Push(s,'c'); Push(s,'d'); Push(s,'e'); if(StackEmpty(s)==1) cout<<"栈为空"<<endl; else cout<<"栈不为空"<<endl; cout<<"出栈队列:"<<endl; while(!StackEmpty(s)) { Pop(s,e); cout<<e<<" "; } cout<<endl; if(StackEmpty(s)==1) cout<<"栈为空"<<endl; else cout<<"栈不为空"<<endl; cout<<"释放栈"<<endl; DestoryStack(s); return 0; }