Last tray on, first tray off

Stacks as Tray Piles

The analogy

Clean trays stack up in the cafeteria. You put a tray on top, and the next person takes the top one โ€” the tray at the bottom has been there since breakfast. You only ever touch the top. That is a stack.

Visualizer

The tray pile

step 1 / 14
bottom

An empty tray pile. There is exactly one place you can reach: the top.empty

๐Ÿ“– In depth โ€” the full reference

Stack operations โ€” all of them

operationmeaningcost
push(x)put x on topO(1)
pop()remove and return the topO(1)
peek / toplook at the top without removingO(1)
isEmptyanything left?O(1)
search / access by depthNOT a stack operationO(n) โ€” if you need it, you wanted a different structure

Where stacks hide

  • The call stack (Module 0's vending machines) โ€” every function call pushes a frame, every return pops one. "Stack overflow" is this stack hitting its ceiling.
  • Undo/redo: two stacks โ€” undo pops from history and pushes onto redo.
  • Matching brackets/tags: push every opener, pop on each closer, and the pairs match iff the stack ends empty.
  • DFS (Module 3) is a stack-driven walk; recursion is DFS borrowing the call stack.

Python: a list IS the stack

stack = []
stack.append(1)      # push โ€” O(1) amortized
stack.append(2)
top = stack[-1]       # peek โ€” O(1)
x = stack.pop()       # pop โ€” O(1), returns 2
if not stack: ...     # isEmpty โ€” empty list is falsy
# Never use insert(0)/pop(0) as a stack โ€” wrong end, O(n)
stack = []
stack.append(4)      # push
stack.append(9)
stack.append(2)

stack.pop()          # 2  โ€” last in, first out
stack[-1]            # 9  โ€” peek

# a plain list IS the idiomatic Python stack
Check yourself

Push 1, 2, 3 then pop. What comes out?

Practice โ€” write it yourself

reverse_with_stack(arr) pushes everything onto a stack (append), then pops it all โ€” returning the reversed list. LIFO doing what LIFO does.

Python 3 ยท runs in your browser ยท your draft is saved locally
๐Ÿ“ My notessaved in this browser