Stacks and Queues
Stack Push/Pop
Push values onto a stack and pop them back in last-in, first-out order.
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> stack = new ArrayDeque<>();
for (int value : new int[] {10, 20, 30}) stack.push(value);
List<Integer> popped = new ArrayList<>();
while (!stack.isEmpty()) popped.add(stack.pop());
System.out.println(render(popped));
}
}
Complexity
- Time: O(1) per push/pop
- Space: O(n)
Implementation notes
- Java declares the stack as
Deque<Integer>and backs it withnew ArrayDeque<>(), using deque methods as stack operations instead of the legacyStackclass.pushandpopoperate at the deque head. - The enhanced
forloop reads primitive values fromnew int[] {10, 20, 30}; eachstack.push(value)autoboxes throughInteger.valueOf, so these small fixture values may be cachedIntegerinstances, and mutates the stack. - Pop uses
while (!stack.isEmpty()) popped.add(stack.pop()).pop()removes the current top and would throw on an empty deque, so theisEmptyguard is the checked empty behavior here. - The replay-visible stack uses logical stack notation, not
ArrayDequeiteration order: it shows[10, 20, 30]after pushes and pops30first, then20and10, producingpopped = [30, 20, 10]. TheArrayDeque,ArrayList, any uncached boxed integers, andStringBuilderoutput are normal JVM heap objects managed by GC.
top
The top is the most recently pushed value.
LIFO
A stack removes values in last-in, first-out order.