Implement Stack using Queues easy
Description
Implement a last-in-first-out (LIFO) stack using only queues. The stack should support:
push(x)— pushxonto the top of the stackpop()— remove and return the top elementtop()— peek at the topempty()— return whether the stack is empty
You may only use the standard queue operations: push to back, pop from front, peek front, size, isEmpty.
Examples
s.push(1)
s.push(2)
s.top() # -> 2
s.pop() # -> 2
s.empty() # -> FalseConstraints
- All calls to
popandtopare on a non-empty stack.
Intuition
A queue gives you the oldest element. A stack wants the newest. We have to invert that somehow.
There are two natural designs:
- Two queues. Use one as the “main” queue, the other as a scratch space.
- One queue, expensive push. After every push, rotate the queue so the just-pushed element ends up at the front.
The one-queue version is simpler — let’s do that.
One-queue trick
Push the new element, then rotate the queue: dequeue size - 1 items and re-enqueue them at the back. The just-pushed element is now at the front, where pop and peek can reach it directly.
start: []
push(1): [1] (no rotation needed)
push(2): [2, 1] after pushing 2 then rotating (move 2 to end? no — see trace below)Trace push(2) carefully:
before push: [1]
after enqueue(2): [1, 2]
rotate (size-1 = 1 time): dequeue 1, enqueue 1
[2, 1] ← 2 is now at the frontThat’s the magic. Every push is O(n), but pop and top are O(1).
Code
Explanation
- After enqueueing the new element, the queue looks like
[old_front, …, old_back, new_x]. - Rotating
n-1times bringsnew_xto the front:[new_x, old_front, …, old_back]. - That makes the rest of the operations trivially O(1).
The reverse problem (“Queue using Stacks”) uses two stacks for amortized O(1) — see the stacks practice section. The asymmetry is interesting: the two structures aren’t equally easy to emulate with each other.
Analysis
- Time:
pushisO(n).pop,top,emptyareO(1). - Space:
O(n).