Stacks and Queues are the operational workhorses of operating systems, programming language runtimes, and mobile UI frameworks.
1. The Call Stack & Execution Frames
Every time a programming language invokes a function, it pushes a stack frame onto the thread's execution call stack.
fun main() {
val a = 10
compute(a)
}
fun compute(x: Int) {
val result = format(x * 2)
println(result)
}
fun format(v: Int): String = "Value: $v"
Stack State when format() is executing:
+-----------------------------------+
| format(v = 20) | <- Top of Stack
+-----------------------------------+
| compute(x = 10, result = ...) |
+-----------------------------------+
| main(a = 10) |
+-----------------------------------+
When format() returns, its frame is popped, restoring the CPU instruction pointer and local registers to compute().
2. Expression Evaluation & Syntax Parsing
Compilers and calculators parse mathematical expressions like 3 + 4 * 2 / ( 1 - 5 ) using Dijkstra's Shunting-Yard Algorithm, which relies on two stacks:
- Operator Stack: Manages operator precedence (
*and/over+and-). - Operand Stack: Holds numerical values during evaluation.
3. Job Scheduling & The Android Looper / MessageQueue
When an Android app runs, the main UI thread executes an infinite loop driven by a Queue:
+----------------------------+
User Tap Event ----> | |
| MessageQueue (FIFO) | ----> Dispatched to Looper
Network Response --> | [ Msg 1 ][ Msg 2 ][ Msg 3]| (Executes on Main Thread)
| |
Frame Render Event-> +----------------------------+
Without a Queue, concurrent background threads would simultaneously mutate UI widgets, causing fatal race conditions.
4. Breadth-First Search (BFS) vs Depth-First Search (DFS)
Stacks and Queues fundamentally govern graph and tree traversals:
- Queue
→BFS (Breadth-First Search): Explores nodes level by level (shortest path discovery). - Stack
→DFS (Depth-First Search): Explores as deep as possible along each branch before backtracking.
Summary
- Stacks manage function call execution, expression evaluation, syntax parsing, and backtracking.
- Queues manage asynchronous event loops, operating system task scheduling, print spools, and BFS graph traversals.