Implement Stack using Queues

Build a stack from a single queue by moving the newest value to the front on every push.

A stack hands back the value that was added last, while a queue hands back the value that was added first. Write a stack class with four methods: push(x) adds x, pop() removes and returns the newest value, top() returns the newest value without removing it, and empty() tells whether the stack holds no values.

The values must be kept in queues, using only what a queue offers: add to the back, remove or look at the front, the size, and whether it is empty. pop() and top() are only called when the stack has values. As an extra challenge, use a single queue.

Example
Input: push(1), push(2), top(), pop(), empty()
Output: top() = 2, pop() = 2, empty() = false
Solution

The Idea

Think of a pile of plates. A clean plate goes on top of the pile, and the next plate you need comes off the top too, so the plate put down last is picked up first. A structure that works like this is called a stack, and the end where values come and go is its top.

A line at a shop counter works the other way round. People join at the back and are served at the front, so whoever came first leaves first. That is a queue.

Look at the example. After push(1) and push(2), top() must give 2 and pop() must remove 2. A queue that received 1 and then 2 has 1 at its front, so removing from it gives 1. How can something that only gives up its oldest value act like something that gives up its newest?

The queue cannot change which end it serves, but we can change the order of the values inside it. If the newest value always sits at the front, then removing from the front is exactly what pop() needs. A new value can only join at the back, though. So after it joins, take each older value off the front and add it again at the back, until the new value reaches the front.

Look at the picture below, where 3 is pushed onto a queue that holds 2 and then 1, front first.

push(3) on a queue holding 2 then 1. Step 1 adds 3 to the back: 2, 1, 3. Step 2 moves 2 from the front to the back: 1, 3, 2. Step 3 moves 1 from the front to the back: 3, 2, 1. Now 3 is at the front.

In the row labelled step 1, 3 joins at the back. In step 2, 2 leaves the front and joins again at the back, and in step 3 the same happens to 1. After one move for each older value, 3 is at the front.

The two older values went round together, so 2 is still ahead of 1. Once 3 is popped, 2 is at the front again, which is what a stack needs: the next newest value is next out. Moving values from the front of a queue to its back like this is called rotating the queue.

Solution Approach

Turning rotation into code means settling three things: which method does the rotating, how many values each push moves, and which queue methods to use. A version with two queues follows as an option.

Which method does the rotating

Could the work go into pop() instead? It could: leave the values in arrival order, and on each pop rotate all of them except the newest, which then reaches the front and can be removed. Either way, one of the methods has to move the values.

Rotating in push(x) keeps the queue in stack order at all times, with the top of the stack at the front of the queue. Then pop() just removes the front, top() looks at it, and empty() asks the queue whether it is empty. If pop() did the rotating, top() would need a rotation of its own. So rotating in push(x) suits programs that pop and look at the top often. Rotating in pop() suits programs that push more often.

How many values each push moves

How many times should the loop rotate? Once x has joined, the queue holds size() values, and all of them except x were there before. Exactly those size() - 1 older values must move behind x. When the queue was empty, that is zero moves, and x is already at the front.

Which queue methods to use

Which Java calls count as queue operations? Java describes a queue with the Queue interface from java.util. Its add puts a value at the back, remove takes the front value off, peek returns the front value without taking it, and size and isEmpty report how many values there are.

The values are stored in an ArrayDeque, a class from java.util that keeps them in a growing array and is a Queue. ArrayDeque also has stack methods of its own, which would make the exercise pointless. Declaring the field with the type Queue means the code can only call the queue methods above.

Two queues instead of one

Many solutions use two queues instead. To push x, add it to the empty second queue, move every value from the first queue into the second, and then swap the two queues' roles. The cost is the same as with rotation. Rotation does the same reordering inside one queue, so the second queue is not needed, which also answers the extra challenge.

Java Solution

The class StackUsingQueue has one field and four methods:

  • queue: an ArrayDeque declared as Queue. Its front is always the top of the stack.
  • push(x): adds x at the back, then a loop with i from 1 while i < queue.size() moves the older values from the front to the back, one at a time.
  • pop(): queue.remove(), which takes the newest value off the front.
  • top(): queue.peek(), which returns the newest value and leaves it in place.
  • empty(): queue.isEmpty().

The main method runs the example, then pushes 3 and 4, prints the queue front first, and pops until the stack is empty.

Java
import java.util.ArrayDeque;
import java.util.Queue;

public class StackUsingQueue {

    private final Queue<Integer> queue = new ArrayDeque<>();  // front of the queue = top

    public void push(int x) {
        queue.add(x);                                  // x joins at the back
        for (int i = 1; i < queue.size(); i++) {
            queue.add(queue.remove());                 // move an older value behind x
        }
    }

    public int pop() {
        return queue.remove();
    }

    public int top() {
        return queue.peek();
    }

    public boolean empty() {
        return queue.isEmpty();
    }

    public static void main(String[] args) {
        StackUsingQueue stack = new StackUsingQueue();
        stack.push(1);
        stack.push(2);
        System.out.println("top() = " + stack.top() + ", pop() = " + stack.pop()
            + ", empty() = " + stack.empty());

        stack.push(3);
        stack.push(4);
        System.out.println("queue, front first: " + stack.queue);
        System.out.println("pops: " + stack.pop() + ", " + stack.pop() + ", " + stack.pop()
            + ", empty() = " + stack.empty());
    }
}

Running it prints:

Output
top() = 2, pop() = 2, empty() = false
queue, front first: [4, 3, 1]
pops: 4, 3, 1, empty() = true

The first line matches the example: top() and pop() both give 2, and with 1 still stored, empty() is false. The second line shows the queue after 3 and 4 were pushed on top of that 1: [4, 3, 1], with 4, the newest, at the front and 1, the oldest, at the back. Popping three times then gives 4, 3 and 1, newest first, and after that empty() is true.

The loop in push(x) starts at 1 so that it runs size() - 1 times. A loop that rotates size() times also moves x, which goes round once and ends up at the back again, so the queue stays in arrival order. Pushing 1, 2 and 3 with such a loop leaves the queue as [1, 2, 3], and pop() returns 1, the oldest value, as a plain queue would.

The original implementation, StackUsingQueue.java, is on GitHub.

Complexity

Only push(x) loops; the other three methods touch just the front of the queue.

  • Time: O(n) for push, O(1) for pop, top and empty, where n is the number of values already on the stack. Each push moves every one of those n values from the front to the back once. ArrayDeque removes or reads its front value, and knows its size, in a fixed number of steps.
  • Space: O(n), because the queue holds one entry per value on the stack, and rotating reuses that same queue instead of building a second one.