Leetcode 0225. Implement Stack using Queues
225. Implement Stack using Queues
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty).
Implement the MyStack class:
void push(int x): Pushes element x to the top of the stack.int pop(): Removes the element on the top of the stack and returns it.int top(): Returns the element on the top of the stack.boolean empty(): Returns true if the stack is empty, false otherwise.
Notes:
- You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid.
- Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.
题目大意
要求仅使用两个队列实现一个 后进先出(LIFO) 的栈,并支持普通栈的全部功能(push、top、pop、empty)。
核心限制:只能使用队列的标准操作(仅允许 push 到队尾、从队首 peek/pop、获取队列大小、判断队列是否为空),不能使用队列之外的其他数据结构特性。
解题思路
队列的特性是 先进先出(FIFO),而栈是 后进先出(LIFO),通过两个队列的 “元素转移” 可模拟栈的顺序,核心思路是 让其中一个队列始终保持 “栈顶元素在队首”,具体如下:
- 划分功能队列:
main_q(主队列):始终存储当前栈的所有元素,且 栈顶元素位于main_q的队首(便于pop和top直接操作队首)。temp_q(临时队列):仅在push新元素时用于暂存main_q的原有元素,辅助调整顺序。
- 核心逻辑:
push:先将新元素压入空的temp_q,再将main_q的所有元素依次转移到temp_q(此时新元素在temp_q队首,即栈顶),最后交换main_q和temp_q的角色(main_q变为新的存储队列,temp_q清空备用)。pop/top:直接操作main_q的队首(因main_q队首就是栈顶),无需额外转移(pop弹出队首,top查看队首)。empty:仅需判断main_q是否为空(temp_q始终为空或仅暂存元素,不存储最终数据)。
1 | #include <queue> |
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.

