C++实现两栈共享空间的进栈、出栈

一、两栈的定义

演示使用了乘2,表示一个栈占10个空间,两个占20

class DoubleStack
{
public:

	DoubleStack(int len)
	{
		this->m_Array = new int[len * 2]{};
		this->m_Idx_One = -1;
		this->m_Idx_Two = len * 2;
		this->m_Len = len * 2;
	}

	void Push(int StackNum, int data);
	void Pop(int StackNum);
	void Print();

	~DoubleStack()
	{
		if (this->m_Array != nullptr)
		{
			delete[] this->m_Array;
			this->m_Array = nullptr;
		}
	}

private:

	int m_Idx_One;
	int m_Idx_Two;
	int m_Len;
	int* m_Array;
};

二、进栈

void DoubleStack::Push(int StackNum, int data)
{
	if (this->m_Idx_One + 1 == this->m_Idx_Two)
	{
		cout << "栈已满" << endl;
	}
	if (StackNum == 1)
	{
		
		this->m_Array[++this->m_Idx_One] = data;
	}
	else if (StackNum == 2)
	{
		this->m_Array[--this->m_Idx_Two] = data;
	}
}

三、出栈

void DoubleStack::Pop(int StackNum)
{
	if (StackNum == 1)
	{
		if (this->m_Idx_One == -1)
		{
			cout << "栈1为空栈,删除错误" << endl;
		}
		this->m_Array[this->m_Idx_One--] = 0;
	}
	else if (StackNum == 2)
	{
		if (this->m_Idx_Two == this->m_Len)
		{
			cout << "栈2为空栈,删除错误" << endl;
		}
		this->m_Array[this->m_Idx_Two++] = 0;
	}
}

四、整体展示

#include <iostream>

using namespace std;


class DoubleStack
{
public:

	DoubleStack(int len)
	{
		this->m_Array = new int[len * 2]{};
		this->m_Idx_One = -1;
		this->m_Idx_Two = len * 2;
		this->m_Len = len * 2;
	}

	void Push(int StackNum, int data);
	void Pop(int StackNum);
	void Print();

	~DoubleStack()
	{
		if (this->m_Array != nullptr)
		{
			delete[] this->m_Array;
			this->m_Array = nullptr;
		}
	}

private:

	int m_Idx_One;
	int m_Idx_Two;
	int m_Len;
	int* m_Array;
};

void DoubleStack::Push(int StackNum, int data)
{
	if (this->m_Idx_One + 1 == this->m_Idx_Two)
	{
		cout << "栈已满" << endl;
	}
	if (StackNum == 1)
	{
		
		this->m_Array[++this->m_Idx_One] = data;
	}
	else if (StackNum == 2)
	{
		this->m_Array[--this->m_Idx_Two] = data;
	}
}

void DoubleStack::Pop(int StackNum)
{
	if (StackNum == 1)
	{
		if (this->m_Idx_One == -1)
		{
			cout << "栈1为空栈,删除错误" << endl;
		}
		this->m_Array[this->m_Idx_One--] = 0;
	}
	else if (StackNum == 2)
	{
		if (this->m_Idx_Two == this->m_Len)
		{
			cout << "栈2为空栈,删除错误" << endl;
		}
		this->m_Array[this->m_Idx_Two++] = 0;
	}
}

void DoubleStack::Print()
{
	for (int i = 0; i <= this->m_Len - 1; ++i)
	{
		cout << this->m_Array[i] << " ";
	}
	cout << endl;
}

void Text()
{
	DoubleStack ds(10);
	ds.Push(1, 10);
	ds.Push(2, 10);
	ds.Push(1, 10);
	ds.Push(2, 10);
	ds.Push(1, 10);
	ds.Print();

	ds.Pop(1);
	ds.Pop(2);
	ds.Print();

}

int main()
{
	Text();

	system("pause");
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值