Log inStart free
LESSON 3.02 · 5 STAGES · 3 CONTROLS · 3 CHECKSPRO · PREVIEW

Stacks and queues

Watch a stack and two queues take the same items and give them back.


Pro lesson. Stage 1 is free to watch. Pro opens all 5 stages, 3 controls and 3 checks, in this lesson and every other.

Go Pro · $8.25/mo
EXPLAINER · 3.02 · QUEUE BAYMOVES · STACK 0 · LIST QUEUE 0 · RING 0
01
Stage 1 of 5 · Push items
Three containers take A to E, one push at a time. The ring buffer writes each item at slot (h + k) mod C.
Explain it simply

You see three containers that get the same letters, A to E. The top two are Python lists, and each new letter goes on the end. The bottom one is a ring buffer, a fixed row of 6 slots. It writes each letter in the next free slot after its head, the slot it reads next.

The stack holds A, B, C, D, E, with E on top. The list queue holds A, B, C, D, E. The ring has 6 slots, head 0 and 5 items: A, B, C, D, E.

itemslot, head, sizemoved or dropped itempopped itemempty slot
containerarray slotspopped, in orderstacklist: append, pop()moves 0list queuelist: append, pop(0)moves 0ring queueh = 0 · k = 5 · C = 6moves 00123401234012345topfrontheadtailmod 6AAABBBCCCDDDEEEmoves so far5 items first14 operations →1901234list queue 0ring queue 0stack 0containerarray slotspopped, in orderstacklist: append, pop()moves 0list queuelist: append, pop(0)moves 0ring queueh = 0 · k = 5 · C = 6moves 00123401234012345topfrontheadtailmod 6AAABBBCCCDDDEEEmoves so far5 items first14 operations →1901234list queue 0ring queue 0stack 0
Toy: 3 containers · 5 to 9 items · a ring of 4 to 8 slots · one fixed program of pushes and pops
STAGE 1 / 5
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
s=(h+k) mod C\sy{s}{param}{s} = (\sy{h}{param}{h} + \sy{k}{data}{k}) \bmod \sy{C}{param}{C}
s=(0+4) mod 6=4(E, then k=5)s = (0 + 4) \bmod 6 = 4\quad(\text{E, then } k = 5)

The ring writes a new item k slots after its head, wrapping at C.

Common mix-ups

MYTHlist.pop(0) is as cheap as list.pop().

The fix, and 1 more mix-up with the diagram to show them, come with Pro.

Predict, then reveal
3 CHECKS · PRO
Q01With 7 items first, how many moves does the list queue make in all?

Make your guess, then test it in the diagram. All 3 checks come with Pro.

PRO LESSON · YOU WATCHED STAGE 1 OF 5
Unlock the full explainer
  • 4 more stages and 3 live controls
  • 2 mix-up cards and 3 predict-then-reveal checks
  • Watch it as a narrated video, in three voices
  • Every Pro lesson and capstone · 656 in total

$99 a year, or $15 a month. Cancel any time.