Stacks and queues both hold a group of things. The big difference is which thing gets to leave first.
A stack is a pile of plates
When you put a clean plate on a pile, it goes on top. When you need a plate, you take the top one. The last plate added is the first plate removed. Programmers call this LIFO: last in, first out.
- Push means put a new item on top.
- Pop means take the top item away.
- Peek means look at the top item without taking it.
A browser’s Back button can use a stack. Every page you visit is pushed on top. When you go back, the newest page is popped away and the page below appears.
A queue is a waiting line
Imagine children waiting for ice cream. The first child to join the line should be the first child served. Programmers call this FIFO: first in, first out.
- Enqueue means join the back of the line.
- Dequeue means let the front item leave.
- Front means look at who is next.
A printer can use a queue. If three people send pages, the printer usually handles the first request first, then the second, then the third.
Choose by the rule
Use a stack when the newest thing should be handled first. Use a queue when the oldest waiting thing should be handled first.
from collections import deque
plates = []
plates.append("blue plate")
plates.append("red plate")
print(plates.pop()) # red plate leaves first
line = deque()
line.append("Mia")
line.append("Leo")
print(line.popleft()) # Mia leaves firstYour tiny challenge
Take three blocks. Make a stack and remove one block. Then make a line and remove one block. Did a different block leave? That small difference is the whole idea.
