Stacks and Queues: Two Simple Rules, Many Uses

Explore last-in-first-out and first-in-first-out structures, with real examples from browsers, scheduling, and search.

By Rishipal Singh · · 5 min read

A stack removes the newest item; a queue removes the oldest.
Visual guide: A stack removes the newest item; a queue removes the oldest.

A stack and a queue are both ordered collections. Their difference is the rule that determines which item comes out next.

Stack: last in, first out

Think of a stack of books: the newest book placed on top is the first one you pick up. A stack supports push to add, pop to remove, and peek to inspect the top. These operations are typically O(1).

Stacks appear in undo history, expression parsing, and function calls. When a function calls another function, the program keeps track of where to return using a call stack.

Queue: first in, first out

A queue behaves like a checkout line: the first person who arrives is served first. Enqueue adds at the back; dequeue removes from the front. A queue can schedule print jobs, process messages in arrival order, or explore a graph one distance layer at a time.

Choose by the order you need

  • Use a stack when the most recent unfinished task should be handled first.
  • Use a queue when waiting tasks should be handled fairly in arrival order.
  • For both, choose an implementation with efficient operations at the ends; removing the first element of a plain array may require shifting everything else.

The structures are small, but the idea of controlling processing order is powerful. Many larger algorithms are built on top of these two simple rules.

Practice: trace a stack

Push A, then B, then C onto an empty stack. Which item does the next pop return?

Reveal the explanation

C is returned first. A stack is last-in, first-out, so the newest item is removed before earlier items.