Stacks & Queues
Fundamental linear data structures with different access patterns
πStack (LIFO)
Last-In, First-Out
Think of a stack of plates. You can only add or remove from the top. The last plate you put on is the first one you take off.
3 β top
2
1
Operations: push (add to top), pop (remove from top), peek (view top)
πΆββοΈQueue (FIFO)
First-In, First-Out
Think of a line at a store. The first person in line is the first to be served. New people join at the back.
front β
1
2
3
β rearOperations: enqueue (add to rear), dequeue (remove from front), peek (view front)
When to Use Which?
Use a Stack when:
- πUndo/Redo - Most recent action should be undone first
- πBrowser History - Back button goes to most recent page
- πFunction Calls - Most recent function returns first
- π€Balanced Parentheses - Match most recent opening bracket
- πReverse Order - Need to process in reverse
Use a Queue when:
- π¨οΈPrint Queue - Documents print in order sent
- β³Task Scheduling - First task submitted runs first
- π³BFS Traversal - Explore level by level
- π«Customer Service - First come, first served
- π¨Message Buffers - Process messages in order
Quick Comparison
| Aspect | Stack | Queue |
|---|---|---|
| Order | LIFO (Last-In, First-Out) | FIFO (First-In, First-Out) |
| Insert | push() - at top | enqueue() - at rear |
| Remove | pop() - from top | dequeue() - from front |
| View | peek() - top element | peek() - front element |
| Time Complexity | O(1) for all operations | O(1) for all operations |
| Java Class | Stack<E> or Deque<E> | Queue<E>, LinkedList<E> |
Explore Topics
Stack Deep Dive
Interactive stack operations, balanced parentheses, and more
- β’ Drag-and-drop push/pop
- β’ Balanced parentheses checker
- β’ Array vs LinkedList implementation
Queue Deep Dive
Interactive queue operations and priority queue concept
- β’ Drag-and-drop enqueue/dequeue
- β’ Priority Queue (ER triage demo)
- β’ Array vs LinkedList implementation
Comparison
Side-by-side comparison and decision guide
- β’ Same operations, different results
- β’ Implementation comparison
- β’ When to use which