Lesson 78: Circular queue
หน้านี้ต้องใช้เบราว์เซอร์ล่าสุด (รองรับ SharedArrayBuffer) กรุณาอัปเดต Chrome, Edge, Firefox หรือ Safari เป็นเวอร์ชันล่าสุด
English
A queue that goes round
- A queue is first in, first out. Items join at the tail and leave at the head.
- In a circular queue the array is used like a circle: after the last place, the pointer goes back to place 0. Places freed at the front are used again.
counttells you if the queue is full (4) or empty (0).
| After | Places 0 1 2 3 | head | tail |
|---|---|---|---|
| add Ann … Dan | Ann Ben Cat Dan | 0 | 0 |
| remove (Ann) | – Ben Cat Dan | 1 | 0 |
| add Eve | Eve Ben Cat Dan | 1 | 1 |

- Robots lesson 47 has a simple queue; this lesson has the fixed-size array version from the A-level exam. Lesson 77 has a stack.
English
In the exam
- 9618/41/M/J/22 Q3: a circular queue of 10 strings in QueueArray, with head pointer, tail pointer and number of items, all starting at 0. (b) Complete Enqueue. Mark scheme: IF NumberItems = 10 THEN RETURN FALSE; QueueArray[TailPointer] ← DataToAdd; IF TailPointer >= 9 THEN TailPointer ← 0 ELSE add 1; NumberItems ← NumberItems + 1. (c) Write Dequeue: it returns "FALSE" if the queue is empty, or the next item.
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
A circular queue of 4 names uses places 0 to 3 of an array. tail is the next free place. When tail passes the end, it goes back to place 0. Finish enqueue: return false when the queue is full; else store the name, move tail on and add 1 to count. Type names; D removes one.
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 4/5 · 280 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Now finish dequeue: take the item at place head, move head on (after place 3 it goes back to 0), subtract 1 from count and return the item. The names must come out in the order they went in.
คลิก Run เพื่อดูผลลัพธ์ที่นี่