Queues are used extensively in operating systems (CPU scheduling, disk scheduling), networking (packet routing, message queues), printing (print spooling), and graph algorithms (BFS — Breadth First Search). The key difference between queues and stacks is that queues process items in arrival order (FIFO) while stacks process the most recent item first (LIFO).
Printer Queue: You, Bob, and Alice all hit 'Print' at the same time. The printer holds the jobs in a Queue and prints yours first (you clicked first), then Bob's, then Alice's. Music Playlist: 'Add to Queue' in Spotify plays songs in the order you added them.
🖨️ The Printer Queue
You, Bob, and Alice hit "Print." Jobs are processed in arrival order.
🎵 Music Playlist
"Add to Queue" in Spotify. Songs play in the order you added them.
💻 CPU Scheduling
OS gives each process a time slice in order. Round Robin uses circular queue!
Tasks wait in a queue to get CPU time.
Documents print in the order they were sent.
Level-by-level traversal uses a queue.
One End (Top)
Two Ends (Front/Rear)
Where Queues Power the Real World
1. The Printer Queue
You, Bob, and Alice all hit "Print" at the same time. The printer can only print one document at a time. So it puts all three jobs in a Queue and processes them in order: yours first (you clicked first), then Bob's, then Alice's. No one's document gets lost or skipped.
2. Music Playlist
When you click "Add to Queue" in Spotify, the song is enqueued at the Rear. Songs play in the order you added them — FIFO.
3. CPU Task Scheduling
Your computer runs dozens of programs at once. The OS puts each process in a queue and gives each a slice of CPU time in order. This is called Round Robin Scheduling (which uses a circular queue!).
4. Breadth First Search (BFS)
In graph traversal, BFS uses a queue to explore all neighbors of a node before moving deeper. This ensures you visit nodes level by level, which is why BFS is perfect for "shortest path" problems in unweighted graphs.
Queue vs Stack — The Big Comparison
| Feature | Stack | Queue |
|---|---|---|
| Principle | LIFO | FIFO |
| Analogy | Pile of plates | Line of people |
| Ends used | One (Top) | Two (Front & Rear) |
| Insert | Push (at Top) | Enqueue (at Rear) |
| Delete | Pop (from Top) | Dequeue (from Front) |
| Use cases | Undo, Recursion, DFS | Scheduling, BFS, Buffers |
Knowing where queues are used in real systems helps you recognize when to apply them in your own code. The Queue vs Stack comparison is one of the most common interview questions and understanding it deeply will save you from many logic errors.
"Why does BFS use a Queue and not a Stack?"
BFS explores nodes level by level (neighbors first, then their neighbors). A Queue processes in FIFO order, which naturally gives this level-by-level traversal. A Stack would give depth-first (DFS) behavior instead.