顺序栈的基本操作:
#include <bits/stdc++.h>
using namespace std;
#define MAXSIZE 10
typedef int ElemType;
//创建栈
typedef struct{
ElemType data[MAXSIZE];
int top;
}SqStack;
//初始栈
void Init_Stack(SqStack *s)
{
s->top=-1;
return ;
}
//进栈
bool Push_Stack(SqStack *s,ElemType e){
if(s->top==MAXSIZE-1)
return false;
s->top++;
s->data[s->top]=e;
return true;
}
//出栈
bool Pop_Stack(SqStack *s,ElemType *e){
if(s->top==-1)
return false;
//cout<<s->top<<endl;
*e=s->data[s->top];
s->top--;
return true;
}
//清空栈
void Clear_Stack(SqStack *s){
while(s->top!=-1){
s->data[s->top]=0;
s->top--;
}
return ;
}
//判断栈非空
bool Empty_Stack(SqStack s){
if(s.top==-1)
return true;
return false;
}
//返回元素个数
int Count_Stack(SqStack s){
return s.top+1;
}
bool Get_Top(SqStack s,ElemType *e) {
if(Empty_Stack(s)){
cout<<"Error:Stack is empty"<<endl;
return false;
}
*e=s.data[s.top];
return true;
}
int main(){
int n;
SqStack s;
Init_Stack(&s);
while(cin>>n&&n){
if(Push_Stack(&s,n)){
cout<<n<<" Push"<<endl;
cout<<"栈元素数量:"<<Count_Stack(s)<<endl;
}
else{
cout<<"The stack is full"<<endl;
}
}
//Clear_Stack(&s);
cout<<"-----------------------------分割线-----------------------------"<<endl;
ElemType e;
while(Pop_Stack(&s,&e)){
cout<<e<<" Pop"<<endl;
cout<<"栈元素数量:"<<Count_Stack(s)<<endl;
if(Get_Top(s,&e))
cout<<"Top:"<<e<<endl;
if(Empty_Stack(s))
cout<<"The stack is empty"<<endl;
}
return 0;
}
顺序栈共享空间的实现:
typedef struct{
ElemType data[MAXSIZE];
int top1;
int top2;
}SqDoubleStack;
bool Push(SqDoubleStack*s,ElemType e, int stackNumber)
{
if(s->top1==s->top2)
return false;
if(stackNumber==1){
s->top1++;
s->data[s->top1]=e;
}
else if(stackNumber==2){
s->top2--;
s->data[s->top2]=e;
}
}
bool Pop(SqDoubleStack* s,ElemType *e,int stackNumber){
if(stackNumber==1){
return false;
s->top1--;
*e=s->data[s->top1];
return true;
}
else if(stackNumber==2){
if(s->top2==MAXSIZE)
return false;
s->top2++;
*e=s->data[s->top2];
return true;
}
return true;
}