LeetCode 题解工作台

用队列实现栈

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作( push 、 top 、 pop 和 empty )。 实现 MyStack 类: void push(int x) 将元素 x 压入栈顶。 int pop() 移除并返回栈顶元素。 int top() 返回栈顶元素。…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 栈·状态

bolt

答案摘要

我们使用两个队列 和 ,其中 用于存储栈中的元素,而 用于辅助实现栈的操作。 - `push` 操作:将元素压入 ,然后将 中的元素依次弹出并压入 ,最后交换 和 的引用。时间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(pushtoppopempty)。

实现 MyStack 类:

  • void push(int x) 将元素 x 压入栈顶。
  • int pop() 移除并返回栈顶元素。
  • int top() 返回栈顶元素。
  • boolean empty() 如果栈是空的,返回 true ;否则,返回 false

 

注意:

  • 你只能使用队列的标准操作 —— 也就是 push to backpeek/pop from frontsize 和 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
  • 最多调用100pushpoptopempty
  • 每次调用 poptop 都保证栈不为空

 

进阶:你能否仅用一个队列来实现栈。

lightbulb

解题思路

方法一:两个队列

我们使用两个队列 q1q_1q2q_2,其中 q1q_1 用于存储栈中的元素,而 q2q_2 用于辅助实现栈的操作。

  • push 操作:将元素压入 q2q_2,然后将 q1q_1 中的元素依次弹出并压入 q2q_2,最后交换 q1q_1q2q_2 的引用。时间复杂度 O(n)O(n)
  • pop 操作:直接弹出 q1q_1 的队首元素。时间复杂度 O(1)O(1)
  • top 操作:直接返回 q1q_1 的队首元素。时间复杂度 O(1)O(1)
  • empty 操作:判断 q1q_1 是否为空。时间复杂度 O(1)O(1)

空间复杂度 O(n)O(n),其中 nn 是栈中元素的个数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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()
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

用队列实现栈题解:栈·状态 | LeetCode #225 简单