Stack using Queues
Implement a last in first out (LIFO) stack using only two queues. The implemented stack should support push, top, pop and empty. void push(int x) pushes element x to the top. int pop() removes and returns the top element. int top() returns the top element. boolean empty() returns true if the stack is empty. Each operation must only use standard queue operations (enqueue to back, dequeue from front, size, isEmpty).
- 1 <= x <= 9
- At most 100 calls to push, pop, top, and empty
- All calls to pop and top are valid
push(1), push(2), top(), pop(), empty()2, 2, falsepush(3), pop(), push(5), top()3, 5Queues are naturally First-In-First-Out, but we want Last-In-First-Out. To turn a flat line into a stack, we need a way to force the newest person to jump all the way to the front of the line.
Think of it as a Line Jumper. When a new person arrives at the back of the queue, we tell everyone in front of them to leave and rejoin the line behind them. By the time everyone has moved, the newcomer is at the very front, ready to be served first.
- Push: This is where all the work happens. We enqueue the new item like normal. Then, we find out how many people were already in line (N). We dequeue those N people one by one and immediately re-enqueue them at the back. Now, our newest item is sitting at the head of the queue.
- Pop/Top: Since we did all the heavy lifting during the Push, these become simple, fast operations. The person at the front of the queue is always the person who arrived last.
CLASS MyStack:
queue = []
FUNCTION push(x):
queue.ENQUEUE(x)
FOR i from 1 to queue.SIZE - 1:
queue.ENQUEUE(queue.DEQUEUE())
FUNCTION pop():
RETURN queue.DEQUEUE()
FUNCTION top():
RETURN queue.PEEK()Circular Queue Rotation for LIFO behavior
The Front-Loading Insight
When pushing a new element, it goes to the back. To make it the top, we rotate all existing elements around it until the new element reaches the front.
Design Trade-off
By doing the work during Push, we keep Pop and Peek extremely fast (O(1)).