All episodes · From a List to Your Map App · Episode 3

Stacks and Queues: Why Undo Goes Backwards

Pressing play loads the video from YouTube.

Type three words and press undo three times: they vanish in reverse. Send three files to a printer: they come out in order. Two simple rules, last in, first out and first in, first out, run a surprising amount of your computer.
We build a stack (push, pop, the undo button, the back button), use one to check brackets the way code editors do, line up a queue (printers, the keys you type), and bend an array into a ring buffer so nothing ever has to move.

Every animation in this video is drawn by code, and the narration is an AI voice.

Transcript

Type three words, then press undo three times. They disappear in reverse: the last one goes first. Now send three files to a printer. They come out in the order you sent them. Two simple rules: last in, first out, and first in, first out. Today: stacks and queues.

A stack is a list where you can only add or take away at one end: the top. Adding is called push. Taking away is called pop. Every undo button is a stack. Each action is pushed, and undo pops the newest one. Your browser's back button works the same way. Every page you open is pushed, and back pops it off. Build it on an array, and push and pop are one step each: just move the top marker.

Stacks can also check your brackets. Read from left to right. Push every opening bracket. Every closing bracket must match the one on top. Round, square, close square, close round. Everything matches, and the stack ends up empty. Now swap two closing brackets. The round one arrives while a square one is on top: a mismatch. Code editors and compilers run this check all day long.

A queue is the other rule. Add at the back, and take from the front. Files sent to a printer wait in a queue, and come out in the order they were sent. The keys you type wait in a small queue too, until the program is ready to read them. That's the keyboard from season one, episode seventeen. Adding at the back is easy. But taking from the front of an array means shifting everything over, like in the last episode.

The trick: don't move the items. Move two markers instead, the front and the back. When the back reaches the end of the array, it wraps around to the start, into the space the front has already left. Bend the array into a ring, and that's a ring buffer. Every step is one move of a marker. Keyboards, sound cards and network cards all keep their data in rings like this.

Stacks: last in, first out. Queues: first in, first out. Both are just an array or a list, plus a rule. Next time, a stack does something surprising: it lets a function call itself. Recursion. See you there.

Next episode: recursion, a function that calls itself.

Buy the Developer a Coffee

Entirely up to you: it works the same either way.

Every cup turns into the next update.

WeChat Pay QR code
WeChat Pay
Alipay QR code
Alipay
PayPal QR code
PayPal