Stacks and Queues

8 min✏️ Quiz at the end

What Is a Data Structure?

A data structure is a way of organising data in memory so that it can be used efficiently. Different structures suit different tasks. Two of the most important — and most widely used — are the stack and the queue.

Both hold a collection of items and support adding and removing items, but they differ in one crucial way: the order in which items come out.


Stacks — Last In, First Out

A stack works exactly like a physical stack of plates. You can only add a plate to the top and only remove a plate from the top. A plate placed on last is the first to come off. This principle is called LIFO — Last In, First Out.

The two core stack operations are:

  • Push — add an item to the top of the stack
  • Pop — remove the item at the top of the stack

A third operation, Peek (or Top), lets you look at the top item without removing it.

Visualising a Stack

Suppose you push the values 10, 20, 30 in that order:

After push(10):  [10]
After push(20):  [10, 20]    ← top is 20
After push(30):  [10, 20, 30] ← top is 30
After pop():     [10, 20]    ← 30 removed, top is now 20

Notice that 30 — the last item added — was the first to leave.

Where Stacks Appear in Real Systems

Stacks are everywhere in computing once you know what to look for:

The call stack. Every time your program calls a function, the computer pushes a frame onto the call stack recording the function's local variables and where to return when it finishes. When the function returns, the frame is popped. This is why recursion can cause a stack overflow — too many frames pushed before any are popped.

Browser history. The Back button in a web browser is a stack. Each page you visit is pushed onto the history stack. Pressing Back pops the current page off and returns you to the previous one.

Undo functionality. Every text editor, drawing tool, or design app that offers Ctrl+Z stores your actions in a stack. Pressing undo pops the most recent action and reverses it.

Expression evaluation. Compilers and calculators use stacks to evaluate mathematical expressions and match pairs of brackets. When a ( is found it is pushed; when a ) is found, the matching ( is popped. If the stack is empty but a ) appears, the expression is invalid.


Queues — First In, First Out

A queue works like a line of people waiting at a bus stop. The first person to join the line is the first person to board the bus. New arrivals join at the back. This principle is called FIFO — First In, First Out.

The two core queue operations are:

  • Enqueue — add an item to the back (rear) of the queue
  • Dequeue — remove the item at the front of the queue

Visualising a Queue

Start:              front → [] ← rear
Enqueue("A"):       front → [A] ← rear
Enqueue("B"):       front → [A, B] ← rear
Enqueue("C"):       front → [A, B, C] ← rear
Dequeue():          front → [B, C] ← rear   (A removed)
Dequeue():          front → [C] ← rear      (B removed)

"A" arrived first and left first — classic FIFO.

Where Queues Appear in Real Systems

Print queues. When multiple documents are sent to a printer, they are stored in a queue and printed in the order they arrived. The document sent first prints first.

CPU task scheduling. Operating systems maintain queues of processes waiting for processor time. A basic scheduler takes the next process from the front and runs it for a time slot, then puts it back at the rear if it isn't finished.

Network buffers. Routers and network switches buffer incoming packets in queues. If packets arrive faster than they can be forwarded, they wait in line. Packets are forwarded in the order they arrived.

Keyboard input. When you type quickly, the characters are stored in an input queue. The processor reads them in the order you pressed the keys, so what you typed appears correctly on screen.


Comparing Stacks and Queues

FeatureStackQueue
PrincipleLIFOFIFO
Add itemPush (to top)Enqueue (to rear)
Remove itemPop (from top)Dequeue (from front)
Real-world exampleUndo history, call stackPrinter queue, network buffer

Overflow and Underflow

Both structures have two important error conditions:

  • Overflow — trying to add an item to a structure that is already full (if it has a fixed maximum size). For a stack: stack overflow. For a queue: queue overflow.
  • Underflow — trying to remove an item from an empty structure. For a stack: stack underflow. For a queue: queue underflow.

Good programs always check whether a stack or queue is full before pushing/enqueuing, and whether it is empty before popping/dequeuing.


Key Words

  • Stack — a LIFO data structure where items are added and removed from the same end (the top)
  • Queue — a FIFO data structure where items are added at the rear and removed from the front
  • LIFO — Last In, First Out
  • FIFO — First In, First Out
  • Push / Pop — the operations for adding to / removing from a stack
  • Enqueue / Dequeue — the operations for adding to / removing from a queue
  • Overflow — error caused by adding to a full structure
  • Underflow — error caused by removing from an empty structure