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.

A stack releases the last that entered; a queue releases the first.
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 in

Why 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 structureWho leavesFits…
A stackThe last that enteredUndo, nesting, returning
A queueThe first that enteredFairness, order of arrival

Example 1 — why a stack fits undo

  1. The last action is the one to undo.
  2. It is also the last that entered.
  3. So the order fits exactly.

Example 2 — why a queue fits waiting

  1. Whoever arrived first waited longest.
  2. A queue releases them first.
  3. So no one is stuck forever.
If both answers hold at once, there are probably two roles in one structure here.