栈的顺序存储结构操作及实现

来源:互联网 发布:js中new date 的参数 编辑:程序博客网 时间:2024/04/19 17:51

栈的顺序存储结构操作及实现

/*栈的顺序存储结构操作及实现 */ #include<iostream>#define MAXSIZE 20using namespace std;typedef int SElemType; //这里用int示例//stack element type 栈中元素的数据类型 typedef struct //栈结构的定义 {SElemType data[MAXSIZE];int top;}SqStack;int Push(SqStack *S,SElemType e)//插入元素e作为新的栈顶元素 {if(S->top==MAXSIZE-1) //栈满{return 0;} S->top++;S->data[S->top]=e;return 1; }int Pop(SqStack *S,SElemType &e)//删除栈顶元素,并用e返回其值 {if(S->top==-1) return 0;e=S->data[S->top];S->top--;return 1;}int main(){int num,n,b,flag;SElemType a; SqStack sta;sta.top=-1;cout<<"请输入要入栈元素的个数:(个数小于等于20)"<<endl;cin>>n;cout<<"请输入元素"<<endl;num=0;for(int i=0;i<n;++i){cin>>a;flag=Push(&sta,a);num+=flag;}if(num==n) cout<<"压栈成功"<<endl;num=0;cout<<"是否弹栈?弹请选择1并输入弹栈数量,否则选2"<<endl;;cout<<"1.弹   2.不弹"<<endl;cin>>b;if(b==1) {cin>>a;for(int i=0;i<a;++i){flag=Pop(&sta,b);num+=flag;if(flag) cout<<"弹了一个元素,该元素为"<<b<<endl;}if(num==a) cout<<"弹栈成功"<<endl; }else ;  return 0;}



1 0
原创粉丝点击