Stacks and Queues· 15 min

Stack (LIFO)

Push and pop — last in, first out

Setup

Current step

Stack initialized with [10, 25, 40].

Step log

[0]10
[1]25
[2]40 Top
↓ push here
Size: 3Top: 40
stack.java
1class Stack<T> {
2 private List<T> items = new ArrayList<>();
3 void push(T x) { items.add(x); }
4 T pop() { return items.remove(items.size() - 1); }
5 T peek() { return items.get(items.size() - 1); }
6 boolean isEmpty() { return items.isEmpty(); }
7}
● Java

Stack (LIFO)

A stack is a Last-In-First-Out structure: the most recently pushed element is the first one popped. Used for function calls, undo history, expression evaluation.

Push/Enqueue
O(1)
Pop/Dequeue
O(1)
Peek/Front
O(1)
Space
O(n)