Question 9b
Write an algorithm to implement a circular queue using array.
Topics: Circular queues
Watch this exact question run
Solution
- front = rear = −1 when empty; all MAX slots usable; full when (rear + 1) mod MAX = front.
Algorithm CQInsert(x)
1. if (rear + 1) mod MAX = front then
2. print "Queue overflow"; return
3. if front = −1 then front ← 0; rear ← 0
4. else rear ← (rear + 1) mod MAX
5. q[rear] ← x
Algorithm CQDelete()
1. if front = −1 then
2. print "Queue underflow"; return
3. item ← q[front]
4. if front = rear then front ← −1; rear ← −1
5. else front ← (front + 1) mod MAX
6. return item| Operation | Result | front, rear | Array (index 0 … 3) | Front → rear |
|---|---|---|---|---|
| insert(10) | ok | 0, 0 | [10 _ _ _] | 10 |
| insert(20) | ok | 0, 1 | [10 20 _ _] | 10 20 |
| insert(30) | ok | 0, 2 | [10 20 30 _] | 10 20 30 |
| insert(40) | ok | 0, 3 | [10 20 30 40] | 10 20 30 40 |
| insert(50) | OVERFLOW | 0, 3 | [10 20 30 40] | 10 20 30 40 |
| delete | removed 10 | 1, 3 | [_ 20 30 40] | 20 30 40 |
| delete | removed 20 | 2, 3 | [_ _ 30 40] | 30 40 |
| insert(50) | ok | 2, 0 | [50 _ 30 40] | 30 40 50 |
| insert(60) | ok | 2, 1 | [50 60 30 40] | 30 40 50 60 |
| insert(70) | OVERFLOW | 2, 1 | [50 60 30 40] | 30 40 50 60 |
MAX = 4. “_” marks a slot that holds no live element.
If your teacher used the Horowitz convention (front = rear = 0 initially, one slot always empty), the full test is the same, but the empty test is front = rear and front is advanced before reading. Either is accepted if stated.
How to write it in the exam
- Empty: front = −1. Full: (rear + 1) % MAX == front.
- Insert: check full; first element → front = rear = 0, else rear = (rear + 1) % MAX; q[rear] = x.
- Delete: check empty; item = q[front]; if front == rear reset to −1, else front = (front + 1) % MAX.
- Number of elements = (rear − front + MAX) % MAX + 1.
How this answer was verified
- tests/linear-expression.test.ts — wrap-around and reference-model tests
- circular_queue.c matches the engine on 200 random cases