CIE AS & A Level Computer Science, section 10.4 (Introduction to Abstract Data Types (ADT))
Queue
A queue is an ADT in which items are added at the rear and removed from the front. It is first in, first out (FIFO), like people waiting in line.
Operations
- Enqueue: add an item at the rear.
- Dequeue: remove and return the item at the front.
- isEmpty / isFull: test the state.
Example
| Operation | Queue (front on the left) |
|---|---|
| enqueue A | A |
| enqueue B | A, B |
| enqueue C | A, B, C |
| dequeue (returns A) | B, C |
| enqueue D | B, C, D |
Implementing with an array
Use two pointers: Front (the first item) and Rear (the last item), and a count of items.
DECLARE Queue : ARRAY[1:5] OF STRING
Front ← 1
Rear ← 0
Count ← 0
PROCEDURE Enqueue(Item)
IF Count = 5 THEN
OUTPUT "Queue full"
ELSE
Rear ← Rear MOD 5 + 1
Queue[Rear] ← Item
Count ← Count + 1
ENDIF
ENDPROCEDURE
Circular queue
In a circular queue, the pointers wrap around to the start of the array after the last position. This reuses the space freed when items are dequeued, instead of running out of room at the end of the array. The MOD 5 above does this.
from collections import deque
q = deque()
q.append("A"); q.append("B"); q.append("C")
print(q.popleft(), list(q)) # A ['B', 'C']
Uses
A printer queue, a buffer, handling requests in order, and scheduling processes.
Common mistake: using a simple (linear) array queue and ending up unable to add items when the front part of the array is empty. A circular queue solves this. Also, a queue removes from the front, not the rear.
Exam tip: give the pointer values after each operation, and explain how the pointers wrap round in a circular queue. Mention FIFO when comparing with a stack.
Check yourself
What does FIFO mean?
First in, first out: the first item added is the first removed.
Which pointer changes when an item is dequeued?
The front pointer.
Why is a circular queue useful?
It reuses the space left by dequeued items, so the queue can keep going without running off the end of the array.