利用两个队列实现一个栈(C++版)

题目:

利用两个队列实现一个栈的功能,完成pop() push() top() empty()等功能。

  • push(x) -- Push element x into stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty

思路:

两个队列q1, q2。不管是插入还是弹出,保证总有一个队列为空。那么:

队列入栈:将元素插入空队列,同时将非空队列的元素依次插入到空队列。此时之前的非空队列变为空队列,空队列变为非空队列。

队列出栈:将非空队列的队首弹出即可。

举例说明:

执行下述操作:先将1 2 3入栈,接着3出栈,然后4入栈。两个队列元素的变化情况如下:

1. 初始:q1 q2为空 将1压入q1。此时q1非空 q2为空。

2. 元素2入栈 q2为空 压入。之前q1非空,将1弹出压入q2。此时q1为空 q2为2 1。

3. 元素3入栈 q1为空 压入。之前q2非空,将2 1依次弹出压入q1。此时q2为空 q1为3 2 1。

4. 元素3出栈 q1非空 3出栈。q1为2 1 q2为空。

5. 元素4入栈 q2为空 压入。之前q1非空,将2 1依次弹出压入q2。此时q1为空 q2为4 2 1。

实现函数代码如下:

class QueueStack {
public:
	// 保证每个时刻都有一个队列为空队列

	// Push element x onto stack.
	void push(int x) {
		if(q1.empty())
		{
			q1.push(x);

			while(!q2.empty())
			{
				q1.push(q2.front());
				q2.pop();
			}
		}
		else
		{
			q2.push(x);

			while(!q1.empty())
			{
				q2.push(q1.front());
				q1.pop();
			}
		}
	}

	// Removes the element on top of the stack.
	void pop() {
		if(q1.empty())
		{
			q2.pop();
		}
		else
		{
			q1.pop();
		}
	}

	// Get the top element.
	int top() {
		if(q1.empty())
		{
			return q2.front();
		}
		else
		{
			return q1.front();
		}
	}

	// Return whether the stack is empty.
	bool empty() {
		return (q1.empty() && q2.empty());
	}

	queue<int> q1;
	queue<int> q2;
};


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值