π PHP Stack & Queue β Topic Index
Stacks (LIFO) and Queues (FIFO) are foundational data structures that power parsing, scheduling, monotonic algorithms, and BFS/DFS traversal.
Topics Covered
| # | Topic | Key Concepts |
|---|---|---|
| 1 | Basics | PHP SplStack, SplQueue, array-as-stack |
| 2 | Patterns | Monotonic stack, deque, two-stack tricks |
| 3 | Interview Questions | 25 classic problems |
When to Use Stack
- Matching brackets / balanced parentheses
- Monotonic next-greater / next-smaller problems
- DFS traversal (explicit stack)
- Undo/redo systems
When to Use Queue
- BFS level-order traversal
- Sliding window maximum (deque)
- Rate limiting / task scheduling
- Implementing other data structures
PHP Data Structures
// Stack (LIFO) β SplStack
$stack = new SplStack();
$stack->push(1);
$top = $stack->top(); // peek
$val = $stack->pop();
// Queue (FIFO) β SplQueue
$queue = new SplQueue();
$queue->enqueue(1);
$front = $queue->bottom(); // peek
$val = $queue->dequeue();
// Array as stack (idiomatic PHP)
$stack = [];
array_push($stack, 1); // or $stack[] = 1;
$top = end($stack); // peek
$val = array_pop($stack);