使用一个数组创建两个栈(方法三)
基本思路:将数组的第一、二个单元作为两个栈的栈底,一个栈使用奇数单元,一个栈使用偶数单元,当两个栈的栈顶都触顶时就认为栈满了,说实话这种方法实现还不如直接用数组创建一个栈。
整体代码:
#include<iostream> //这个程序只考虑了长度为偶数的情况
const int stacksize=10;
typedef struct Stack{
int data[stacksize];
int top1=0;
int top2=1;
}Stack;
using namespace std;
int Isempty(Stack*);
int Isfull(Stack*);
int Push(Stack*,int,int);
int Pop(Stack*);
int main(void){
Stack p;
int choice,x;
while(!Isfull(&p)){
cout<<"请输入你要存入的数据"<<endl;
cin>>x;
cout<<"请选择存入栈一还是栈二"<<endl;
cin>>choice;
Push(&p,x,choice);
}
while(!Isempty(&p)){
x=Pop(&p);
cout<<x<<endl;
}
return 0;
}
int Isempty(Stack* p){
return p->top1==0&&p->top2==1;
}
int Isfull(Stack* p){
return p->top1==stacksize-2&&p->top2==stacksize-1;
}
int Push(Stack* p,int x,int choice){
if(Isfull(p)){
cout<<"The stack is full"<<endl;
exit(0);
}
if(choice==1&&p->top2<stacksize-2){
p->top1+=2;
p->data[p->top1]=x;
}else if(choice==2&&p->top2<stacksize-1){
p->top2+=2;
p->data[p->top2]=x;
}else return 0;
return 1;
}
int Pop(Stack* p){
if(Isempty(p)){
cout<<"The stack is empty"<<endl;
exit(0);
}
int x=0;
if(p->top1>0){
x=p->data[p->top1];
p->top1-=2;
}else{
x=p->data[p->top2];
p->top2-=2;
}
return x;
}