InteractLab

InteractLabStacks & Queues

Stacks & Queues — plates you pile, lines you join

Two ways to hold a row of things, told apart by one question: who leaves first? A stack is a pile of plates — the last one you put down is the first you pick up (LIFO). A queue is a line at the coffee shop — whoever arrived first is served first (FIFO). Push and pop the pile, join and leave the line, and watch each rule play out one step at a time.

Module 1A stack — last in, first out
topstack[-1]3719
Step 1 / 1Push, pop, or peek the stack.
1 / 1
Space play/pause · ←→ step · Home/End jump · R replay
stack.pypython
1stack = []             # a plain list is all you need2 3stack.append(9)        # push — 9 goes on top4stack.append(4)        # push — 4 is the new top5stack[-1]              # peek — read the top (4), leave it6stack.pop()            # pop  — remove & return the top (4)7len(stack)             # -> 1   ·  every line here is O(1)
Module 2A queue — first in, first out
frontbackdequeueenqueue →5q[0]284q[-1]
Step 1 / 1Enqueue, dequeue, or peek the queue.
1 / 1
Space play/pause · ←→ step · Home/End jump · R replay
queue.pypython
1from collections import deque2 3q = deque([5, 2, 8])   # front is 5, back is 84q.append(4)            # enqueue — 4 joins the back5q.popleft()            # dequeue — 5 leaves the front (-> 5)6q[0]                   # peek — the front is now 27len(q)                 # -> 3   ·  append & popleft are O(1)
Module 3What they’re really made of

Stack = a plain list

The end of the list is the top. Adding and removing there never disturb the other items, so both stay fast.

stack.append(x)O(1)
stack.pop()O(1)

Queue ≠ a plain list

Removing from the front of a list re-indexes every item behind it. Reach for collections.deque, built to be fast at both ends.

list.pop(0)O(n)
deque.popleft()O(1)
Module 4Where you meet them in the wild
Stacks show up as

Undo / redo

Every action you take is pushed onto a stack. Undo pops the most recent one back off.

The browser Back button

Each page you visit is pushed; Back pops you to the page right before it.

The call stack

Function calls stack up and unwind in reverse — the exact stack recursion runs on.

Matching brackets

Push each opening bracket, pop on every closing one. Empty at the end means the brackets balance.

Queues show up as

Print jobs

Documents print in the order you sent them — first in, first out.

Message & task queues

Work is added at the back and handled from the front, strictly in arrival order.

Breadth-first search

Exploring a tree or graph level by level keeps a queue of the nodes still to visit.

Customer service lines

Whoever called first is answered first — the everyday queue you already know.

Module 5Cheat sheet
StructureAddRemovePythonCost
Stack (LIFO)push append()pop pop()listO(1)
Queue (FIFO)enqueue append()dequeue popleft()collections.dequeO(1)