Lesson contents

Stacks

A stack adds and removes items at the same end, called the top. The last item added is the first one removed.

Simple example

Push 2, then 5, then 8. Pop once and print the value that came off the top.

Start2 5 8
Result8
main.swift
var stack = [0, 0, 0]
let items = [2, 5, 8]
var size = 0
while size < 3 {
    stack[size] = items[size]
    size += 1
}
size -= 1
print(stack[size])
Output
8
Advertisements

Everyday examples

Lift the top workbook

Workbooks 12, 17 and 21 land on a desk in that order. Which can you lift without moving another book?

Start12 17 21
Result21

Book 21 is on top. Lifting it exposes 17.

Undo a drawing

A learner draws a circle, adds a line, then adds a dot. Undo twice. What is left?

Start○ ─ •
Result○

Pop the dot first and the line second. The circle was the earliest change and remains.

Retrace a walk

You visited rooms 4, 6 and 9. Log each room as you enter. If you leave 9 and retrace one step, where are you?

Start4 6 9
Result6

Remove the current room from the stack. Room 6 is now on top.

Cost and limits

Check for an empty stack before popping. A linked stack can push or pop in constant time. A growing array occasionally resizes.