scrolls

where thought scrolls on

Stacks vs. Queues

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.

Download PDF Study Card


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 top
  • pop(): Remove the top item
  • peek(): 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 end
  • dequeue(): Remove item from the front
  • peek(): 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

FeatureStack (LIFO)Queue (FIFO)
Primary UseCall history, recursionScheduling, buffering
Access PatternTop-onlyFront-only
OperationsPush/Pop/PeekEnqueue/Dequeue/Peek
Time ComplexityO(1) for all opsO(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.