两栈共享空间的基本实现

是两个顺序栈,采用想向存储的方式

在入栈,出栈,取栈顶元素,判空时要明确是对哪一个栈进行的操作

栈满的条件: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;
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值