栈实验(两栈共享空间)

栈实验(两栈共享空间)

两个栈共享一个存储空间,该方法对于两个栈对空间需求刚好相反时很有用,即一个栈增大,另一个栈必然减小的情况

头文件

#pragma once
const int STACKSIZE = 100;
class BothStack
{
public:
	BothStack() { //初始化两个空栈
		top1 = -1; //栈1的栈顶游标
		top2 = STACKSIZE; };//栈2的栈顶游标
	~BothStack() {};
	void push(int i, int x);//i压栈x
	void pop(int i);//i出栈
	int getTop(int i);//返回i栈的栈顶元素
	bool empty(int i);//返回i栈是否尾空
private:
	int data[STACKSIZE];//两栈共用的空间
	int top1, top2;//两栈游标
};

源文件

#include "BothStack.h"
void BothStack::push(int i, int x) {
	switch (i)
	{
	case 1:
		if (top1 == top2-1)throw"栈满溢出";
		top1++;
		data[top1] = x;
		break;
	case 2:
		if (top1 == top2-1)throw"栈满溢出";
		top2--;
		data[top2] = x;
		break;
	default:
		break;
	}
}

void BothStack::pop(int i) {
	switch (i)
	{
	case 1:
		if (top1 == -1)throw"栈空下溢";
		top1--;
		break;
	case 2:
		if (top2 == STACKSIZE)throw"栈空下溢";
		top2++;
		break;
	default:
		break;
	}
}

bool BothStack::empty(int i) {
	switch (i)
	{
	case 1:
		if (top1 == -1)return  true;
		return false;
		break;
	case 2:
		if (top2 == STACKSIZE)return  true;
		return false;
		break;
	default:
		break;
	}
}

int BothStack::getTop(int i) {
	switch (i)
	{
	case 1:
		return data[top1];
		break;
	case 2:
		return data[top2];
		break;
	default:
		break;
	}
}

测试文件

#include<iostream>
using namespace std;
#include"BothStack.h"

int main() {
    BothStack st;
    cout << "判断栈1是否为空:" << st.empty(1) << endl;
    cout << "判断栈2是否为空:" << st.empty(2) << endl;
    //栈1压栈3个元素
    st.push(1, 10);
    st.push(1, 20);
    st.push(1, 30);
    //栈2压栈3个元素
    st.push(2, 100);
    st.push(2, 200);
    st.push(2, 300);
    cout << "取栈1栈顶元素:" << st.getTop(1) << endl;
    cout << "取栈2栈顶元素:" << st.getTop(2) << endl;
    //栈1弹栈2个元素
    st.pop(1);
    st.pop(1);
    //栈2弹栈2个元素
    st.pop(2);
    st.pop(2);
    cout << "再取一次栈1栈顶元素:" << st.getTop(1) << endl;
    cout << "再取一次栈2栈顶元素:" << st.getTop(2) << endl;
    cout << "再次判断栈1是否为空:" << st.empty(1) << endl;
    cout << "再次判断栈2是否为空:" << st.empty(2) << endl;
}

测试结果

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值