使用一个数组建立两个栈(方法二)
基本思路;两个栈顶从中间分别向两边扩展,当触碰到了两边的边界就认为栈满了,我觉得我使用的第一种用一个数组创建两个栈的方法比这个要好,从两边向中间扩展对资源的利用更好且更灵活。
问题;我刚开始在写的时候没有充分考虑到数组越界的问题,经过后面的调试发现的,以后在使用数组时多考虑。
整体代码:
#include<iostream>
const int stacksize=10;
typedef struct Stack{
int data[stacksize];
int top1=stacksize/2-1;
int top2=stacksize/2;
}Stack;
using namespace std;
int Isempty(Stack*); //判栈空
int Isfull(Stack*); //判栈满
int Push(Stack*,int,int); //入栈
int Pop(Stack*); //出栈
int main(void){
Stack s;
int x,choice,i=0;
while(!Isfull(&s)/*i<stacksize-2*/){
cout<<"输入一个数字"<<endl;
cin>>x;
cout<<"请选择第一个栈还是第二个栈"<<endl;
cin>>choice;
Push(&s,x,choice);
i++;
}
while(!Isempty(&s)){
x=Pop(&s);
cout<<x<<endl;
}
return 0;
}
int Isempty(Stack* p){
return p->top1>=stacksize/2-1&&p->top2<=stacksize/2;
}
int Isfull(Stack* p){
return p->top1==0&&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->top1>0){
p->data[--p->top1]=x;
}else if(choice==2&&p->top2<stacksize-1){
p->data[++p->top2]=x;
}else return 0;
return 1;
}
int Pop(Stack* p){
if(Isempty(p)){
cout<<"The stack is empty"<<endl;
return 0;
}
int x;
if(p->top1<stacksize/2-1){
x=p->data[p->top1++];
}else{
x=p->data[p->top2--];
}
return x;
}