Lesson 11 of 12
Learn the stack (last in, first out) and the queue (first in, first out) with flowchart blocks: push, pop, enqueue and dequeue, drawn as they change.
About 6 minutes · 3 parts, each with a program to try
Part 1 of 3
A stack is like a pile of plates: you push a plate on top, and pop the top one off. The last one in is the first one out.
It's how Undo works: every change is pushed, and Undo pops the last one.
changes = []"Undo: " + undone"Still done: " + join(changes)Undo: made it boldStill done: typed Hellochanges = []changes.append("typed Hello")changes.append("made it bold")undone = changes.pop()print("Undo: " + undone)print("Still done: " + ", ".join(changes))Part 2 of 3
A queue is like a line at a counter: people enqueue at the back, and the one at the front is dequeued first.
Printers, messages and turns in a game all wait in queues.
line = []"Serving " + next"Serving " + nextServing ArunServing Priyaline = []line.append("Arun")line.append("Priya")line.append("Kavin")next = line.pop(0)print("Serving " + next)next = line.pop(0)print("Serving " + next)Part 3 of 3
Push every letter of a word onto a stack, then pop them all: they come off backwards.
Repeat While length(stack) > 0 keeps popping until the stack is empty.
word = "code"stack = []letter in wordRepeat →
back to the top for the next lap
backwards = ""length(stack) > 0Repeat →
backwards to backwards + letterback to the top for the next lap
backwardsedocword = "code"stack = []for letter in word: stack.append(letter)backwards = ""while len(stack) > 0: letter = stack.pop() backwards = backwards + letterprint(backwards)Quick check