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)xpop()top()empty()
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()top()
Example
Output: top() = 2, pop() = 2, empty() = false
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)push(2)top()pop()
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()
Look at the picture below, where 3 is pushed onto a queue that holds 2 and then 1, front first.
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()
Rotating in push(x)pop()top()empty()pop()top()push(x)pop()
How many values each push moves
How many times should the loop rotate? Once xsize()xsize() - 1xx
Which queue methods to use
Which Java calls count as queue operations? Java describes a queue with the Queuejava.utiladdremovepeeksizeisEmpty
The values are stored in an ArrayDequejava.utilQueueArrayDequeQueue
Two queues instead of one
Many solutions use two queues instead. To push x
Java Solution
The class StackUsingQueue
: anqueue declared asArrayDeque . Its front is always the top of the stack.Queue : addspush(x) at the back, then a loop withx from 1 whilei moves the older values from the front to the back, one at a time.i < queue.size() :pop() , which takes the newest value off the front.queue.remove() :top() , which returns the newest value and leaves it in place.queue.peek() :empty() .queue.isEmpty()
The main
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:
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()pop()empty()false[4, 3, 1]empty()true
The loop in push(x)size() - 1size()x[1, 2, 3]pop()
The original implementation,
Complexity
Only push(x)
- 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.
removes or reads its front value, and knows its size, in a fixed number of steps.ArrayDeque - 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.