Lesson 47: First in, first out
Wait in line
- A queue keeps items in the order they arrive. New items join at the back; items leave from the front.
- This is FIFO: first in, first out, like people waiting at a counter.
- A stack (lesson 21) is the opposite: LIFO, last in, first out.
Words for this lesson
| Word | Meaning |
|---|---|
| queue | first in, first out |
| enqueue | add an item at the back: queue.append(x) |
| dequeue | take the item at the front: queue.pop(0) |
| front / rear | the oldest item / the newest item |
Map 2, step by step
| Step | Queue (front first) | Serve |
|---|---|---|
| after the orders | blue, red, red, red | |
| 1 | red, red, red | blue |
| 2 | red, red | red |
| 3 | red | red |
| 4 | (empty) | red |
- With
pop()the robot would serve red, red, red and then blue: the first customer waits longest.
In the exam
- Queues and stacks are A Level (9618) data structures.
- 9618/22/M/J/23 Q3(a)(i): a circular queue of 10 locations holds Red, Green, Blue, Pink in locations 5 to 8 (front pointer at 5, end pointer at 8). Describe how Orange and Yellow are added. Mark scheme: check that the queue is not full; the end pointer moves to 9, Orange is stored there; the end pointer wraps round to 0, Yellow is stored there.
- The front pointer does not move: items are only added at the end, as with
append.
רמת קושי 3/5 · 200 מטבעות + בונוס קטן בהשלמה הראשונה היום
A café robot takes orders. It drives over 4 tiles: each red tile is an order for the red table, each blue tile for the blue table. Add each order to the חזרה / אחורה of the list queue with append. The program prints the queue, for example Queue: red, blue, blue, red.
לחץ על הרץ כדי לראות את התוצא כאן.
רמת קושי 4/5 · 280 מטבעות + בונוס קטן בהשלמה הראשונה היום
The robot serves the orders, driving to each table (red on the left, blue on the right) and back. But queue.pop() takes the newest order first: that is a stack, so on map 2 the customers are served in the wrong order. Serve them in the order they came, first in, first out: take the order at the חזית of the queue. The numbered circles show the right order.
לחץ על הרץ כדי לראות את התוצא כאן.