Building Blocks of Program Flow
Introduction
Every programmer, from novice to ninja, eventually meets two key data structures: Stacks and Queues. They’re deceptively simple — but incredibly powerful. Understanding them is essential for managing program state, controlling flow, and solving real-world problems.
What Is a Stack?
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. Imagine stacking plates — the last one you put on top is the first one you remove.
Stack: []
🧠 Use Cases:
- Undo/redo functionality
- Function call tracking (call stacks)
- Syntax parsing (e.g., brackets, expressions)
Operations:
push(item)
: Add item to the toppop()
: Remove the top itempeek()
: View the top item without removing it
Time Complexity:
- Push, Pop, Peek:
O(1)
Python Stack Example
stack = []
stack.append("A")
stack.pop()
What Is a Queue?
A queue is a linear structure that follows the First In, First Out (FIFO) principle — like waiting in line at a coffee shop.
Queue: []
🧠 Use Cases:
- Task scheduling
- Printer jobs
- Real-time streaming or buffering
Operations:
enqueue(item)
: Add item at the enddequeue()
: Remove item from the frontpeek()
: View the front item without removing it
Time Complexity:
- Enqueue, Dequeue, Peek:
O(1)
Python Queue Example
from collections import deque
queue = deque()
queue.append("A")
queue.popleft()
JavaScript Queue Example
let queue = []
queue.push("A")
queue.shift()
⚔️ Stacks vs Queues
Feature | Stack (LIFO) | Queue (FIFO) |
---|---|---|
Primary Use | Call history, recursion | Scheduling, buffering |
Access Pattern | Top-only | Front-only |
Operations | Push/Pop/Peek | Enqueue/Dequeue/Peek |
Time Complexity | O(1) for all ops | O(1) for all ops |
🧠 Final Thoughts
Though simple in nature, stacks and queues serve as foundational components in larger systems. From compilers to OS schedulers, they power logic beneath the surface.
💡 Pro Tip: Know the access pattern you need. If it’s last-in-first-out, use a stack. If it’s first-in-first-out, go with a queue.