Learn / Stacks and queues

Implementation

A stack adds and removes at one end: last in, first out. A queue adds at the back and removes at the front: first in, first out. Both can sit on an array (with a top index, or a head index that wraps round) or on a linked list. Every operation is O(1).

How to recognise it

  • The problem asks you to build push, pop, top or enqueue and dequeue yourself.
  • Things must come back out in reverse order (stack) or arrival order (queue).
  • A recursive solution needs to hold values while it works on the rest: the call stack is a stack.
  • Several stacks or queues must share one fixed block of memory.

The two shapes

Adds atRemoves fromOrder out
Stacktoptopnewest first (LIFO)
Queuebackfrontoldest first (FIFO)

A stack of plates and a line at a ticket counter are the usual pictures. A deque (double-ended queue) allows both ends, so it can act as either.

On an array

  • Stack: keep size. The top is data[size - 1]. Push writes data[size] and adds 1; pop subtracts 1. When the array is full, a growing stack copies into an array twice as big; a fixed stack reports overflow.
  • Queue: keep head and size. The front is data[head] and the back slot after it is (head + size) mod capacity. Removing moves head forward by one, wrapping to 0. This wrap is what makes it a circular queue: no slot is wasted and nothing is shifted.

On a linked list

  • Stack: push puts a new node before the head; pop removes the head.
  • Queue: keep head and tail. Add after the tail, remove the head. When the last node leaves, set the tail to null as well.

Sharing one array

Two stacks can grow towards each other from the two ends; the array is full when the tops meet. For k stacks or queues, give every slot a next index. Free slots form one linked list, and each stack (or queue) is its own linked list through the same array.

The call stack is a stack

A recursive function that takes a value off, recurses, and puts it back is using the call stack to hold values. That is how you can insert at the bottom of a stack, reverse it or sort it with no second container.

Common mistakes

  • Forgetting the empty check before pop or top.
  • In an array queue, moving items left after every removal (O(n)) instead of moving head.
  • In a list queue, leaving tail pointing at a removed node once the queue is empty.

Problems

0 of 22 solved

Check yourself

You push 1, 2, 3 onto a stack and pop once. What comes out?

You add 1, 2, 3 to a queue and remove once. What comes out?

In an array queue of capacity 4, head = 3 and size = 2. Which slot holds the back item?

Why does a linked-list stack push and pop at the head?