A stack of plates (last in, first out)
Push plates onto a stack, pop them off and peek at the top. See why the last plate you put on is always the first one you take off, and what happens when you try to pop from an empty stack.
Core concept
A stack keeps items in a pile: push puts an item on the top, pop takes the top item off and peek only looks at it, so the last item in is the first one out (LIFO)
Topic: Data structures
A stack is a way of keeping items in order, like a pile of plates in the kitchen. You can only put a new plate on the top, and you can only take the top plate off. Putting an item on is called push, taking the top item off is called pop, and looking at the top item without taking it is called peek. Because you always work at the top, the last item you pushed is the first one you pop: last in, first out, or LIFO. Computers use stacks everywhere. The undo button in a text editor keeps your changes on a stack, so undo takes back your latest change first, and a web browser's back button returns to the page you opened last.
What you will learn
- Push, pop and peek on a stack and say what each one does.
- Predict which item comes off a stack after a list of operations.
- Explain last in, first out (LIFO) with an everyday example.
- Explain why a pop from an empty stack is not allowed.
Before you start
- Know what a list (a row of items in order) is.
Materials
- A notebook to write your predictions
Equipment
- None
Procedure
- Push a plate onto the stack and see where it goes.
- Pop a plate off and see which one leaves.
- Peek at the top and check that nothing is taken off.
- Pop until the stack is empty, then try one more pop.
- Answer the practice challenges.