LeetCode题目:用队列实现栈

本文介绍了一种使用两个队列实现栈数据结构的方法。通过在输入队列和输出队列间转移元素,可以实现栈的基本操作如push、pop和top。此方法巧妙地利用了队列的先进先出特性来模拟栈的后进先出行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用两个队列实现栈

首先用两个队列模拟栈,两个队列是输入队列InputQueue和输出队列OutputQueue。

  1. -push:直接将输入的数据压入InputQueue.
  2. -pop:假设InputQueue有N个数据,将N-1个数据压入OutputQueue,将InputQueue中的最后一个数据弹出,并将InputQueue执行pop操作,清空队列,执行pop操作。执行完成之后将OutputQueue中的数据重新压入InputQueue中。
  3. -top:假设InputQueue有N个数据,将N-1个数据压入OutputQueue,将InputQueue中的最后一个数据返回,执行top操作,将最后一个数据重新压入OutputQueue,并将InputQueue执行pop操作,清空队列。执行完成之后将OutputQueue中的数据重新压入InputQueue中。
    在这里插入图片描述
#include<queue>
#include<iostream>
using namespace std;
class MyStack {
public:
	/** Initialize your data structure here. */
	MyStack() {}
	/** Push element x to the back of queue. */
	void push(int x) {
		InputQueue.push(x);
	}
	/** Removes the element from in front of queue and returns that element. */
	int pop() {
		while (InputQueue.size() != 1)
		{
			OutputQueue.push(InputQueue.front());
			InputQueue.pop();
		}
		int top = InputQueue.front();
		InputQueue.pop();
		while (!OutputQueue.empty())
		{
			InputQueue.push(OutputQueue.front());
			OutputQueue.pop();
		}
		return top;
	}
	/** Get the front element. */
	int top() {
	 
		while (InputQueue.size() != 1)
		{
			OutputQueue.push(InputQueue.front());
			InputQueue.pop();
		}
		int top = InputQueue.front();
		InputQueue.pop();
		OutputQueue.push(top);
		while (!OutputQueue.empty())
		{
			InputQueue.push(OutputQueue.front());
			OutputQueue.pop();
		}
		return top;
	}
	/** Returns whether the queue is empty. */
	bool empty() {
		if (OutputQueue.empty() && InputQueue.empty())
			return true;
		return false;
	}
private:
	queue<int> InputQueue;
	queue<int> OutputQueue;
};
int main()
{
	MyStack  stk;
	stk.push(1);
	stk.push(2);
	cout<< stk.top() << endl;
	cout << stk.pop() << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值