#include <iostream>
using namespace std;
const int size=50;
typedef int StackElement;
class DoubleStack
{
private:
StackElement array[size];
int frontTop;
int backTop;
public:
DoubleStack()
{
frontTop=-1;
backTop=size;
}
bool empty() const;
bool full() const;
void frontPush(StackElement item);//前端入栈
void backPush(StackElement item);//后端入栈
void frontPop(); //前端出栈
void backPop(); //后端出栈
void display();
};
bool DoubleStack ::empty() const
{
if(frontTop==-1&&backTop==size)
{
cout<<"栈已满"<<endl;
return true;
}
else
{
return false;
}
}
bool DoubleStack :: full() const
{
if(frontTop>=backTop-1)
{
cout<<"栈全空"<<endl;
return true;
}
else
{
return false;
}
}
void DoubleStack ::frontPush(StackElement item)
{
frontTop+=1;
if(!full())
{
array[frontTop]=item;
}
}
void DoubleStack ::backPush(StackElement item)
{
backTop-=1;
if(!full())
{
array[backTop]=item;
}
}
void DoubleStack ::frontPop()
{
if(!empty())
{
frontTop-=1;
cout<<"前端栈出栈成功!"<<endl;
}
}
void DoubleStack ::backPop()
{
if(!empty())
{
backTop+=1;
cout<<"后端栈出栈成功!"<<endl;
}
}
void DoubleStack ::display()
{
cout<<"前端栈:";
int i=0,j=0;
while(i<=frontTop)
{
if(j%5==0)
cout<<endl;
cout<<array[i]<<" ";
j++;
i++;
}
cout<<endl;
i=size-1;
j=0;
cout<<"后端栈:";
while(i>=backTop)
{
if(j%5==0)
cout<<endl;
cout<<array[i]<<" ";
j++;
i--;
}
cout<<endl;
}
void main(void)
{
//初始化双端栈
DoubleStack *s;
s=new DoubleStack;
int temp;
int t=-1;
cout<<"选项: 1-前端入栈 2-后端入栈 3-前端出栈 4-后端出栈 5-双端栈显示"<<endl;
while(1)
{
cout<<"输入选项:";
cin>>t;
if(t==1)
{
cout<<"输入入栈元素:";
cin>>temp;
s->frontPush(temp);
}
else if(t==2)
{
cout<<"输入入栈元素:";
cin>>temp;
s->backPush(temp);
}
else if(t==3)
{
s->frontPop();
}
else if(t==4)
{
s->backPop();
}
else if(t==5)
{
s->display();
}
else
cout<<"请重新输入:"<<endl;
}
}