07. (附加)用两个队列实现栈(C++版本)

实现思路:
需要始终保持其中一个队列为空,记空队列为队列A,另外一个为队列B
插入元素(Push())时,插入队列B。
弹出栈顶元素(Pop()),将队列B中全部弹出然后插入到队列A,直到剩余一个元素为止。然后弹出剩余的这个元素。
获取栈顶元素(Top()),只需返回队列B的队尾元素。

实现的栈类型为NewQueue,包括的成员函数如下

bool Empty()
因为不知道哪个队列中有数据,所以两个队列都需要判断。
std::size_t Size()
因为不知道哪个队列中有数据,所以加上两个队列的元素个数即可。
int Top()
哪个队列有数据,就获它的队尾数据。
void Push(int newData)
如果一个队列为空,加入到另外一个队列中即可。
void Pop()
将非空的队列中所有元素弹出然后压入到另外一个非空列队,直到剩下一个元素为止。然后弹出剩余的这个元素。

实现代码:
头文件NewStack.h

#include <queue>

class NewStack
{
public:
	bool Empty();
	std::size_t Size();
	int Top();
	void Push(int newData);
	void Pop();

private:
	void TransferToOtherAndRemainOne(std::queue<int>& queue1, std::queue<int>& queue2);

private:
	std::queue<int> m_queue1;
	std::queue<int> m_queue2;
};

实现文件NewStack.cpp

#include "NewStack.h"

bool NewStack::Empty()
{
	return m_queue1.empty() && m_queue2.empty();
}

std::size_t NewStack::Size()
{
	return m_queue1.size() + m_queue2.size();
}

int NewStack::Top()
{
	if (m_queue1.empty()) return m_queue2.back();
	else return m_queue1.back();
}

void NewStack::Push(int newData)
{
	if (m_queue1.empty()) m_queue2.push(newData);
	else m_queue1.push(newData);
}

void NewStack::Pop()
{
	if (m_queue1.empty())
	{
		TransferToOtherAndRemainOne(m_queue2, m_queue1);
		m_queue2.pop();
	}
	else
	{
		TransferToOtherAndRemainOne(m_queue1, m_queue2);
		m_queue1.pop();
	}
}

void NewStack::TransferToOtherAndRemainOne(std::queue<int>& from, std::queue<int>& to)
{
	if (from.empty()) return;

	while (from.size() > 1)
	{
		to.push(from.front());
		from.pop();
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值