双栈共享一个栈空间
为什么要使用共享栈:可能某一个栈空间不够用,总是需要扩容,而另一个栈总是有空间闲置,将两个栈的空间共享。
解决方式:将编号为 0 和 1 的两个栈存放于一个数组空间 V [m]中,栈底分别处于数组的两端。当第 0 号栈的栈顶指针 top [0] 等于-1 时该栈为空,当第 1 号栈的栈顶指针 top [1] 等于 m 时该栈为空。两个栈均从两端向中间增长。
代码如下:
#include<iostream>
using namespace std;
#define MaxSize 100
typedef struct{
int top[2]; //栈顶指针
int bot[2]; //栈底指针
int data[MaxSize];
}DblStack; //共享栈
//初始化
bool InitStack(DblStack& s){
s.bot[0] = s.top[0] = -1;
s.bot[1] = s.top[1] = MaxSize;
return true;
}
//判空
bool IsEmpty(DblStack& s,int i){
return s.top[i] == s.bot[i];
}
//判满
bool IsFull(DblStack& s){
return s.top[0] + 1 == s.top[1];
}
//入栈
bool DblPush(DblStack& s,int x,int i){
if(IsFull(s)) return false;
if(i == 0) s.data[++s.top[0]] = x;
else s.data[--s.top[1]] = x;
return true;
}
//出栈
bool DblPop(DblStack &s,int& x,int i){
if(IsEmpty(s,i)) return false;
if(i == 0) x=s.data[s.top[0]--];
else x=s.data[s.top[1]++];;
return true;
}
int main(){
DblStack s;
InitStack(s);
cout<<IsEmpty(s,0)<<" "<<IsEmpty(s,1)<<endl;
DblPush(s,1,0);
DblPush(s,1,1);
cout<<IsEmpty(s,0)<<" "<<IsEmpty(s,1)<<endl;
int x;
DblPop(s,x,0);
cout<<x<<endl;
DblPop(s,x,1);
cout<<x<<endl;
cout<<IsEmpty(s,0)<<" "<<IsEmpty(s,1)<<endl;
}
执行结果: