顶对顶堆栈代码

#include <iostream>
using namespace std;
/*const int max=100;*/
template <class T>
class facestack
{
 public:
  facestack(int size);
  ~facestack(){}
  void push(T x,int i);
  T pop(int i);
  T Top(int i);
  bool empty(int i);
 private:
  int top[2];
  int end[2];
  T *stacka;
  int maxsize;
};
template <class T>
facestack<T>::facestack(int size)
{
 top[0]=-1;end[0]=top[0];top[1]=size;end[1]=top[1];
 maxsize=size;
 stacka=new T [size];
 if(stacka==NULL)
 {cerr<<"动态存储分配栈1失败"<<endl;
 exit(1);
 }
}
template <class T>
void facestack<T>::push(T x,int i)//将x压入第i个堆栈
{    int p,q;
     if(top[1]==top[0])cout<<"堆栈满了,无法进行入栈操作";
    else{
          if(i==1)
     {top[0]++;p=top[0];
     stacka[p]=x;
             }
     if(i==2)
     {top[1]--;q=top[1];
     stacka[q]=x;
             }
             }
}
template <class T>
T  facestack<T>::pop(int i)//出栈操作,将第i个堆栈的栈顶元素输出
{int x;
if(empty(i))cerr<<"堆栈已空";
    else
    {
    if(i==1){x=stacka[top[0]];top[0]--;return(x);
             }
    if(i==2){x=stacka[top[1]];top[1]++;return(x);
             }        
      }
}
template <class T>
T facestack<T>::Top(int i)
{
 if(empty(i))cout<<"堆栈"<<i<<"已空,栈顶没有值"<<endl;
 else {
     if(i==1)return(stacka[top[0]]);
     if(i==2)return(stacka[top[1]]);
                      }
                      }
template <class T>
bool facestack<T>::empty(int i)//检查第i个堆栈是否为空
{
     return(top[i-1]==end[i-1]);
     }
int main()
{
   int j,i,x;
   int max=100;
 facestack<int> s(max);
 cout<<"面对面堆栈初始化……"<<endl;
     cout<<"***************************************************"<<endl;
  cout<<"【1】入栈;【2】输出栈顶元素;";cout<<"【3】出栈;【4】退出;"<<endl;
  cout<<"***************************************************"<<endl;
  cout<<"输入操作";
  cin>>i;
  while(i!=4)
  {
   if(i==1)
            {
                    cout<<"【1】入栈…";
                    cout<<"堆栈i:";
                    cin>>j;
                    cout<<"入栈数据:";
                    cin>>x;
                    s.push(x,j);
                    }
   if(i==2)
            {
                    cout<<"【2】输出栈顶元素…"<<endl;
                    cout<<" …………《选择堆栈》…………"<<endl<<"《1.堆栈1》…………《2.堆栈2》"<<endl;
                    cin>>j;
                    cout<<"读第"<<j<<"堆栈栈顶元素";
                    cout<<s.Top(j)<<endl;
                    }
   if(i==3)
            {
                    cout<<"【3】出栈操作…"<<endl;
                    cout<<" ………『选择堆栈』………"<<endl<<"『1.堆栈1』……『2.堆栈2』"<<endl;
                    cin>>j;
                    cout<<"将第"<<j<<"堆栈出栈";
                    cout<<s.pop(j)<<endl;
                    }
                    cout<<"输入操作";
   cin>>i;
  }

}

 


 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值