Foundations · Unit 9
Stacks and Queues
Sometimes the order you handle things in is the whole problem. Process them newest-first and you get one behavior. Process them oldest-first and you get a completely different one. Stacks and queues are the two data structures that lock in those two orders.
A stack is last in, first out. Picture a stack of plates: you add to the top and take from the top, so the last plate you set down is the first one you pick up. A queue is first in, first out. Picture a line at a coffee shop: people are served in the order they arrived, first to show up is first to leave.
They are simple, and that simplicity is the point. By restricting how you add and remove, they make certain problems fall apart neatly. This unit covers both, the operations they support, and the signal that tells you which one a problem is quietly asking for.
You’re not signed in. Your progress here won’t be saved.
The stack: last in, first out
A stack only lets you touch one end, the top. You push to add a value on top, and you pop to remove the value currently on top. That is it. You cannot reach into the middle or the bottom.
Because you always take from the top, the most recently added item is the first one to come back out. That is "last in, first out," or LIFO. Stack three plates labeled 1, 2, 3 in that order, and the first one you lift off is 3, the last one you put down.
You push 1, then 2, then 3 onto a stack, then pop once. What value comes off?
The drills and graded test are premium
The lessons above are free. The interactive practice that turns recognizing the pattern into recalling it on a blank page unlocks with premium:
- ✓2 applied drills: train spotting when the concept applies
- ✓A 5-question graded test to clear the unit
- ✓The full guided problem ladder with faded hints, plus the cold-read capstone
From $6/month. Cancel anytime.