⚡Flashcard Drill➔
NeetCode #346LC-225EasyStackNC 250
← Back to All Problems

#346 · #225 · Implement Stack using Queues(用队列实现栈)

📌 Problem Statement & Constraints

Implement a last-in-first-out stack using only two queues, supporting push, pop, top and empty. Constraints: 1 <= x <= 9; at most 100 calls.

💡 Core Algorithmic Approaches

  1. The trick is to make push rotate the queue so the newest element is always at the front.
  2. Push the new element at the back, then rotate the other size - 1 elements from the front to the back.
  3. After the rotation, pop and top are simply front operations, both O(1).
  4. A single queue suffices -- the second queue is unnecessary for this rotation trick.

💻 Benchmark Python3 Implementation

class MyStack:
    def __init__(self):
        from collections import deque
        self.q = deque()

    def push(self, x: int) -> None:
        self.q.append(x)
        # rotate so the newest element comes to the front
        for _ in range(len(self.q) - 1):
            self.q.append(self.q.popleft())

    def pop(self) -> int:
        return self.q.popleft()            # front is the newest

    def top(self) -> int:
        return self.q[0]

    def empty(self) -> bool:
        return not self.q

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n) for push (the rotation) and O(1) for everything else. An alternative makes push O(1) and pop O(n).
💾 Space Complexity
O(n) for the queue.

⚠️ Interview Pitfalls & Follow-ups

  • Rotating len(self.q) times instead of len(self.q) - 1: the newest element would move back to the rear, defeating the purpose.
  • Using two queues: unnecessary; the rotation trick needs only one.
  • Making pop O(n) instead of push: both are valid designs, but be clear about which operation carries the cost.
  • Using q[-1] for top: after the rotation the newest element is at index 0, not -1.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Stack Problems

中文速览与面试要点

用队列实现栈

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。实现 MyStack 类: push(x) 将元素 x 压入栈顶; pop() 移除并返回栈顶元素; top() 返回栈顶元素; empty() 如果栈是空的,返回 true;否则返回 false。注意:你只能使用队列的基本操作 —— 也就是 push to back 、 peek/pop from front 、 size 和 is empty 这些操作;你所使用的语言也许不支持队列。你可以使用 list(列表)或者 deque(双端队列)来模拟一个队列,只要是标准的队列操作即可。约束:1 ≤ x ≤ 9;最多调用 100 次 push、pop、top 和 empty;题目数据保证每次调用 pop 和 top 都保证栈不为空。

核心要点

  • 单队列 + 入队时旋转(最优解) :只用一个队列。 push(x) 时先把 x 入队,然后把队列中 前面已有的所有元素 依次移到队尾。
  • 为什么这样能实现 LIFO :旋转后,新元素被移到了队首,因此队首永远是「最后压入的元素」, pop 只需 popleft() 。
  • 复杂度 : push 为 O(n)(旋转 n−1 次), pop / top / empty 为 O(1)。
  • 双队列方案 :主队列存数据,辅助队列用于在 push 时腾挪,效果相同但需要管理两个队列。

常见陷阱

  • push 时旋转次数写成 len(self.q) :会把新元素自己也旋转一次,导致它跑到队尾。应为 len(self.q) - 1 。
  • pop 用 self.q.pop() :那是弹出队尾(即最早入队的元素),是 FIFO 而非 LIFO。必须用 popleft() 。
  • 用 list 而非 deque :list 的 pop(0) 是 O(n),会让旋转操作退化为 O(n²)。必须用 deque。
  • top 用 self.q[-1] :那是队尾(最早入队),不是栈顶。

参考实现

from collections import deque

class MyStack:
    def __init__(self):
        self.q = deque()

    def push(self, x: int) -> None:
        self.q.append(x)
        # 把前面已有的元素全部移到队尾,使新元素位于队首
        for _ in range(len(self.q) - 1):
            self.q.append(self.q.popleft())

    def pop(self) -> int:
        return self.q.popleft()         # 队首即栈顶

    def top(self) -> int:
        return self.q[0]

    def empty(self) -> bool:
        return not self.q