LeetCode 题解工作台
用队列实现栈
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作( push 、 top 、 pop 和 empty )。 实现 MyStack 类: void push(int x) 将元素 x 压入栈顶。 int pop() 移除并返回栈顶元素。 int top() 返回栈顶元素。…
3
题型
6
代码语言
3
相关题
当前训练重点
简单 · 栈·状态
答案摘要
我们使用两个队列 和 ,其中 用于存储栈中的元素,而 用于辅助实现栈的操作。 - `push` 操作:将元素压入 ,然后将 中的元素依次弹出并压入 ,最后交换 和 的引用。时间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路
题目描述
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x)将元素 x 压入栈顶。int pop()移除并返回栈顶元素。int top()返回栈顶元素。boolean empty()如果栈是空的,返回true;否则,返回false。
注意:
- 你只能使用队列的标准操作 —— 也就是
push to back、peek/pop from front、size和is empty这些操作。 - 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
示例:
输入: ["MyStack", "push", "push", "top", "pop", "empty"] [[], [1], [2], [], [], []] 输出: [null, null, null, 2, 2, false] 解释: MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // 返回 2 myStack.pop(); // 返回 2 myStack.empty(); // 返回 False
提示:
1 <= x <= 9- 最多调用
100次push、pop、top和empty - 每次调用
pop和top都保证栈不为空
进阶:你能否仅用一个队列来实现栈。
解题思路
方法一:两个队列
我们使用两个队列 和 ,其中 用于存储栈中的元素,而 用于辅助实现栈的操作。
push操作:将元素压入 ,然后将 中的元素依次弹出并压入 ,最后交换 和 的引用。时间复杂度 。pop操作:直接弹出 的队首元素。时间复杂度 。top操作:直接返回 的队首元素。时间复杂度 。empty操作:判断 是否为空。时间复杂度 。
空间复杂度 ,其中 是栈中元素的个数。
class MyStack:
def __init__(self):
self.q1 = deque()
self.q2 = deque()
def push(self, x: int) -> None:
self.q2.append(x)
while self.q1:
self.q2.append(self.q1.popleft())
self.q1, self.q2 = self.q2, self.q1
def pop(self) -> int:
return self.q1.popleft()
def top(self) -> int:
return self.q1[0]
def empty(self) -> bool:
return len(self.q1) == 0
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | and space complexity depend on the chosen approach: the two-queue method results in O(n) push and O(1) pop/top, whereas the single-queue rotation method has O(n) push with O(1) pop/top. Space is O(n) in both cases for queue storage. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ask candidates to implement a stack with strict queue-only operations to test understanding of LIFO vs FIFO behavior.
- question_mark
Check if the candidate optimizes push or pop; performance trade-offs reveal problem-solving depth.
- question_mark
Listen for discussion about top element tracking or queue rotation as a method to preserve stack order.
常见陷阱
外企场景- error
Attempting to access the last element directly without rotation or auxiliary storage violates queue-only rules.
- error
Confusing push and pop time complexity and not accounting for O(n) rotations in single-queue approaches.
- error
Neglecting to update the top variable when popping can lead to incorrect top() results.
进阶变体
外企场景- arrow_right_alt
Implement a stack using only a single queue without auxiliary variables.
- arrow_right_alt
Optimize for frequent top() calls while minimizing rotations on push().
- arrow_right_alt
Design a double-ended stack using two queues to allow both front and back LIFO operations.