两个栈共享同一存储空间


#include <iostream>
using namespace std;

const int StackSize = 100;

class BothStack
{

private:
    int data[StackSize];  ///存放两个栈的数组
    int top1, top2; ///两个栈的栈顶指针,分别为各自栈顶元素在数组中的下标

public:
    BothStack() {
        top1 = -1;
        top2 = StackSize;
    }  ///构造函数,将两个栈分别初始化
    ~BothStack() {} ///析构函数为空
    void Push(int i, int x); //入栈操作,将元素x压入栈i
    int Pop(int i);  ///出栈操作,对栈i执行出栈操作)
    int Empty(int i) {
        if (top1 == -1 && top2 == StackSize)
            return 1;
        else
            return 0;
    }  ///判断栈是否为空

};

void BothStack::Push(int i, int x) ///入栈操作,将元素x入栈
{
    if (top1 == top2 - 1)  throw "上溢"; ///判断是否栈满
    if (i == 1)  data[++top1] = x; ///在栈1中插入
    if (i == 2)  data[--top2] = x; ///在栈2中插入
}

int BothStack::Pop(int i)  ///出栈操作,将栈顶元素弹出
{
    if (i == 1) { ///在栈1中删除
        if (top1 == -1) ///判断栈1是否为空
            throw "下溢";
        return data[top1--];
    }
    if (i == 2) { ///在栈2中删除
        if (top2 == StackSize) ///判断栈2是否为空
            throw "下溢";
        return data[top2++];
    }
}

int main()
{
	BothStack B;
	B.Push(1,1);
	B.Push(2,2);
	B.Push(1,3);
	B.Push(2,4);
	cout << B.Pop(1) <<endl;
	cout << B.Pop(1) <<endl;
	cout << B.Empty(1) <<endl;
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值