Imagine you have two magic toy boxes: one where you can only add or take toys from the top, and another like a train line where toys go in one end and out the other. Today, let's play with stack and queue — super fun boxes that follow simple rules, just like stacking blocks or lining up for ice cream!
Stack: The Cookie Tower Game
A stack is like building a tower of cookies. You can only put a cookie on top or take one from the top. The last cookie you add is the first one you eat!
Real-life examples:
- Stacking plates: the top one gets washed first
- Undo button in games: removes the last move you made
Try it with simple code (Python):
cookie_tower = [] # Empty tower
# Add cookies (on top)
cookie_tower.append("chocolate")
cookie_tower.append("strawberry")
print("Tower:", cookie_tower) # ['chocolate', 'strawberry']
# Take cookie (from top)
top_cookie = cookie_tower.pop()
print("Eat:", top_cookie) # strawberry
print("Left:", cookie_tower) # ['chocolate']
Rule: Last In, First Out (LIFO) — like undoing your latest drawing stroke!
Queue: The Line-Up Train
A queue is like kids waiting for the school bus. The first kid in line gets on first! Toys go in at the back and leave from the front.
Real-life examples:
- Buying tickets at the movies: first to arrive, first to enter
- Printer jobs: first file sent prints first
Try it with simple code (Python):
train_line = [] # Empty line
# Join line (at back)
train_line.append("Amy")
train_line.append("Ben")
print("Line:", train_line) # ['Amy', 'Ben']
# Leave line (from front)
first_out = train_line.pop(0)
print("Next:", first_out) # Amy
print("Left:", train_line) # ['Ben']
Rule: First In, First Out (FIFO) — fair and orderly, like recess lines!
How to Play Right Now
Get started:
- Open Python on your computer (or use python.org online)
- Copy the code into a file called
toy_boxes.py - Run it:
python toy_boxes.pyin command line
What you'll see:
Tower: ['chocolate', 'strawberry']
Eat: strawberry
Left: ['chocolate']
Line: ['Amy', 'Ben']
Next: Amy
Left: ['Ben']
Where Do They Hide in Real Life?
- Stack: Browser back button, puzzle game moves
- Queue: Supermarket checkout, video game wait lists
You're now a toy box master! Add "apple" or "banana" to both and see who comes out first. So much fun — try it and share with friends! 🚂🍪
Top comments (0)