CAP7004 · Unit 2: Linear data structures
Queues, circular queues and deques
8 practice questions
Key points
- Queue is FIFO; deque gives O(1) at both ends
- Avoid list.pop(0); use collections.deque
- Circular queue uses (index + 1) % capacity
- Two stacks can simulate a queue
A queue is First-In-First-Out (FIFO): enqueue at the rear, dequeue from the front. Used for task scheduling, BFS, printer spooling and buffering.
Python: do not use list.pop(0) for queues (O(n)). Use collections.deque: append, popleft, appendleft, pop are all O(1). deque(maxlen=k) keeps only the last k items. rotate(2) moves the last two items to the front.
Circular queue: a fixed-size array where indices wrap around using modulo, rear = (rear + 1) % capacity, so freed front slots are reused. A queue of capacity 5 whose rear is at index 4 moves to index 0 on the next enqueue. To tell full from empty, keep a size counter or leave one slot unused.
Deque (double-ended queue): insert and remove at both ends. Priority queue: removes the highest-priority item first (see heaps).
Two stacks make a queue: enqueue pushes onto stack A; dequeue pops from stack B, refilling B from A (reversing order) only when B is empty. Dequeue is amortized O(1).
Try two questions
deque([1, 2, 3, 4, 5], maxlen=3) contains:
- 3, 4, 5
- 1, 2, 3
- 2, 4, 5
- 1, 2, 5
Show the answer
A. With maxlen, old items fall off the opposite end as new ones arrive.
Which Python class gives O(1) removal from the front of a queue?
- list
- tuple
- collections.deque
- set
Show the answer
C. deque.popleft() is O(1), while list.pop(0) is O(n).