Implement Stack Using Queues
Implement a stack using only two queues. You may only use standard queue operations: enqueue (push to back), dequeue (pop from front), peek (front), and empty check. The stack must support push(x), pop(), top(), and empty(). The key insight: a stack is LIFO while a queue is FIFO. By using an auxiliary queue and moving elements around, the newest element can be kept at the front of the main queue. This teaches how data structures can implement each other and reveals the fundamental relationship between LIFO and FIFO.
The key insight is that a stack reverses order (LIFO) while a queue preserves order (FIFO). To make a queue behave like a stack, you need to reverse the order of elements each time a new element is pushed. This can be done by pushing the new element into an empty auxiliary queue, then moving all elements from the main queue to the auxiliary queue, and finally swapping the two queues. This puts the newest element at the front of the main queue, ready to be popped first.
An alternative approach is to make the push operation O(1) and the pop operation O(n), by pushing directly and rotating elements when popping. Both are valid.
Example Input & Output
Push 1,2. Top is 2. Pop 2. Not empty.
Push 1, pop 1. Empty.
Algorithm Flow
Solution Approach
Implement a stack using two queues. The stack must support push, pop, top, and empty operations. Use one queue as the primary storage and the other as temporary space. On push, add the element to the back of the primary queue. On pop/top, rotate all elements except the last from the primary queue to the temporary queue, then process the last element and swap the queue roles.
Transferring n-1 elements to the other queue leaves the last element at the front for O(n) pop/top. The queue that holds the actual elements alternates between q1 and q2 after each operation.
Time complexity is O(1) for push, O(n) for pop/top, space is O(n).
Best Answers
import java.util.*;
class MyStack {
Queue<Integer> q1 = new LinkedList<>();
Queue<Integer> q2 = new LinkedList<>();
public void push(int x) {
q2.add(x);
while (!q1.isEmpty()) q2.add(q1.poll());
Queue<Integer> t = q1; q1 = q2; q2 = t;
}
public int pop() { return q1.poll(); }
public int top() { return q1.peek(); }
public boolean empty() { return q1.isEmpty(); }
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
