Lesson 47: First in, first out
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
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 |
English
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.
English
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.
点击“运行”查看此处输出。