Grade 10 Computer Science · Stacks, queues and trees
The order in which things leave
Two structures with the same items and two different answers.
The same three items, and who leaves first?
Three items go into a structure, one after another. There are two entirely different answers to who leaves first, and both are correct. But one of them may leave someone waiting forever. Which one, and when does that even matter?
In earlier units you chose a data structure by how it is accessed — by position, by name, or merely to check existence. Now a second dimension enters: when the structure holds things waiting to be handled, the important question is who leaves first. Exactly the same items, and two entirely different answers.
stack = []
stack.append("a"); stack.append("b"); stack.append("c")
print(stack.pop()) # c — the last in
from collections import deque
queue = deque()
queue.append("a"); queue.append("b"); queue.append("c")
print(queue.popleft()) # a — the first inWhy this is not merely a question of convenience
It is easy to think the difference is small and can always be fixed later. In practice the order settles the system’s behaviour under load. A queue guarantees that no request stays stuck forever, because every new request joins at the back. A stack guarantees the opposite: under load, the old items at the bottom may wait indefinitely. If the structure holds people rather than data, that difference is a difference in fairness and not in performance.
| The structure | Who leaves | Fits… |
|---|---|---|
| A stack | The last that entered | Undo, nesting, returning |
| A queue | The first that entered | Fairness, order of arrival |
Example 1 — why a stack fits undo
- The last action is the one to undo.
- It is also the last that entered.
- So the order fits exactly.
Example 2 — why a queue fits waiting
- Whoever arrived first waited longest.
- A queue releases them first.
- So no one is stuck forever.