Stacks and Queues
Queue from Two Stacks
Implement queue behavior with an input stack and an output stack.
Algorithm
Basic Implementation
Basic.java
import java.util.*;
public class Basic {
static String render(List<Integer> values) {
StringBuilder out = new StringBuilder();
for (int i = 0; i < values.size(); i++) {
if (i > 0) out.append(" -> ");
out.append(values.get(i));
}
return out.toString();
}
public static void main(String[] args) {
Deque<Integer> inStack = new ArrayDeque<>();
Deque<Integer> outStack = new ArrayDeque<>();
for (int value : new int[] {10, 20, 30}) inStack.push(value);
while (!inStack.isEmpty()) outStack.push(inStack.pop());
List<Integer> removed = new ArrayList<>();
while (!outStack.isEmpty()) removed.add(outStack.pop());
System.out.println(render(removed));
}
}
Complexity
- Time: O(1) amortized per operation
- Space: O(n)
Implementation notes
- Java declares both stacks as
Deque<Integer>and backs them withnew ArrayDeque<>(), using deque operations as stack operations rather than the legacyStackclass.pushandpopoperate at the deque head. - The enhanced
forloop reads primitive values fromnew int[] {10, 20, 30}; eachinStack.push(value)autoboxes throughInteger.valueOf, so these small fixture values may be cachedIntegerinstances, and mutates the input stack. - Transfer is explicit: while
inStackis not empty,outStack.push(inStack.pop())pops the newest input-stack value and pushes it onto the output stack, reversing stack order so lateroutStack.pop()calls produce FIFO queue order. - The replay-visible states use logical stack notation, not
ArrayDequeiteration order:ingrows to[10, 20, 30], transfer leavesinempty andoutas[30, 20, 10], thenremovedbecomes[10, 20, 30]. The twoArrayDequeinstances,ArrayList, any uncached boxed integers, andStringBuilderoutput are normal JVM heap objects managed by GC.
input stack
Enqueue pushes new values onto the input stack.
output stack
When the output stack is empty, transferring all input values reverses them into dequeue order.