Data Structure: 3. Two Queues Make A Stack

Problem Discription:

[exercise 10.1-7 from CLRS]
Show how to implement a stack using two queues. Analyze the running time of the stack operations.

You may assume that the queue operations enqueue, dequeue, and isEmpty are provided. You should provide the stack operations push, pop and isEmpty.

Your task is to implement stacks using two queues, as directed above.


There are basically two ways to approach the problem, one that is efficient when pushing an element and one that is efficient when popping an element. We’ll call the two queues Q1 and Q2.

Efficient pushing: To push an element, enqueue the new element to Q1. To pop an element, dequeue everything except the last element from Q1 and enqueue the elements on Q2, dequeue the last element from Q2 and save it, swap the two queues, and return the saved element.

Efficient popping: To push an element, enqueue the new element to Q2, dequeue everything from Q2 and enqueue the elements on Q1, and swap the two queues. To pop the stack, dequeue the first element of Q1 and return it.

The isEmpty operation simply checks if both queues are empty. In both cases the time complexity is constant for the efficient operation but the other operation is linear in the number of elements in the stack, because each operation has to touch each element.