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
Use two queues. For push, enqueue to q2, move everything from q1 to q2, swap q1 and q2. The newest element is always at q1 front. Pop, top, and empty just work on q1.
Push O(n), others O(1). Space 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.
