Stacks and Queues
A stack is Last In, First Out (LIFO) - like a pile of plates. A queue is First In, First Out (FIFO) - like a ticket line. In Java, use ArrayDeque for both (it's faster than the old Stack class).
Stacks and queues control processing order. ArrayDeque handles both efficiently, and monotonic stacks solve 'next greater element' problems in linear time.
Example
Balanced brackets
Example
Next greater element (monotonic stack)
Example
Each index is pushed and popped once, so this is O(n), not O(n²).
Key points
- Stack is LIFO; queue is FIFO.
- Use ArrayDeque for both.
- Monotonic stacks solve next-greater problems.
📝 Test yourself
1. A stack is...
2. Which class is recommended for stacks and queues in Java?
3. Fill in the queue method that removes the first item:
queue.()
