是两个顺序栈,采用想向存储的方式
在入栈,出栈,取栈顶元素,判空时要明确是对哪一个栈进行的操作
栈满的条件:top2=top1+1
两个栈空的条件:top=-1;top2=stacksize;
#include<iostream>
using namespace std;
const int StackSize=100;
template<class DataType>
class BothStack
{
private:
DataType data[StackSize];
int top1,top2;
public:
BothStack();//构造函数
~BothStack(){}//析构函数
void Push(int i,DataType x);//入栈,将元素x压入栈i
DataType Pop(int i);//出栈,取出栈i的元素
DataType getTop(int i);//取出栈i的栈顶元素
int Empty(int i);//判断栈i是否为空
};
template<class DataType>
BothStack<DataType>::BothStack()
{
top1=-1;
top2=StackSize;
}
template<class DataType>
void BothStack<DataType>::Push(int i,DataType x)
{
if(top1==top2-1) throw "上溢";//判断是否栈满
if(i==1)
{
top1+=1;
data[top1]=x;
}
if(i==2)
{
top2-=1;
data[top2]=x;
}
}
template<class DataType>
DataType BothStack<DataType>::Pop(int i)
{
DataType x;
if(i==1)
{
if(top1==-1)throw "下溢";
x=data[top1];
top1-=1;
}
if(i==2)
{
if(top2==StackSize)throw "下溢";
x=data[top2];
top2+=1;
}
return x;
}
template<class DataType>
DataType BothStack<DataType>::getTop(int i)
{
DataType x;
if(i==1)
{
if(top1==-1) throw "下溢";
x=data[top1];
}
if(i==2)
{
if(top2==StackSize) throw "下溢";
x=data[top2];
}
return x;
}
template<class DataType>
int BothStack<DataType>::Empty(int i)
{
if(i==1)
{
if(top1==-1)
return 1;
else
return 0;
}
if(i==2)
{
if(top2==StackSize)
return 1;
else
return 0;
}
}
int main()
{
BothStack<int> bs1;
for(int i=0;i<5;i++)
{
int a[5];
cin>>a[i];
bs1.Push(1,a[i]);
}
while(bs1.Empty(1)!=1)
{
cout<<bs1.Pop(1)<<endl;
}
return 0;
}