1-min guide

Stacks and queues

Stacks and queues are the classic containers for holding data temporarily. The only difference is “in what order things come out” — but that difference changes a lot about what you can do with them.

Reading time: about 1 min

More in the 5-min version →

In the game, this was a ramen shopPlay “Plates & the Ramen Line”

In the gameIn real IT
BowlData
Bowl pile (take from the top)Stack (LIFO)
Waiting line (out from the front)Queue (FIFO)
Stack / Take toppush / pop
Line up / Take frontenqueue / dequeue
Stack (pile)123pushpop → 3The last one in, 3, comes out first (LIFO)Queue (line)123enqueuedequeue → 1The first in line, 1, comes out first (FIFO)
Put in 1, 2, 3 in that order: the stack gives back 3 first, the queue gives back 1 first

Stack = last in, first out (LIFO)

Like a pile of plates, you add to the top and take from the top. Putting in is called push and taking out is called pop. Ctrl+Z (undo) and the browser’s “Back” button pile your history of actions on a stack and take them off newest first.

Queue = first in, first out (FIFO)

Like a checkout line, you join at the back and leave from the front. Putting in is called enqueue and taking out is called dequeue. A printer’s print queue and the requests waiting to be processed by a server are queues.

StackQueue
Order outNewest firstOldest first
AbbreviationLIFOFIFO
Put in / take outpush / popenqueue / dequeue
Everyday examplesA pile of plates, undoA checkout line, print queue

How the FE exam asks it

A common question: “Push 1, 2, 3 onto an empty stack in that order, then pop twice. What remains?” With a stack, 3 and 2 come out and 1 remains. Do the same with a queue, and 1 and 2 come out and 3 remains.

Summary
  • A stack is last in, first out (LIFO): push and pop
  • A queue is first in, first out (FIFO): enqueue and dequeue
  • “Undo” is a stack; a “line of tasks waiting” is a queue
Go further: 5-min deep diveStacks and queues in depth: function calls, Reverse Polish notation and message queuesThe stack running inside programs every second, Reverse Polish notation (an exam classic), and the queues that connect systems.Read the 5-min version →