TExcelTAD

Queues

A queue is a collection where the first item added is the first one removed: FIFO (first in, first out). It is a line at a ticket counter: people join at the back and are served from the front.

Operations

Operation Meaning Cost (good implementation)
enqueue(x) add x at the back O(1)
dequeue() remove and return the front item O(1)
peek() look at the front item O(1)
is_empty(), size() O(1)

The wrong way: list.pop(0)

A Python list can act as a queue with append and pop(0), but pop(0) shifts every remaining element one slot left, so each dequeue is O(n). Let's count the moves:

python · try it yourself
def dequeue_cost(n):
    queue = list(range(n))
    moves = 0
    while queue:
        moves += len(queue) - 1     # pop(0) shifts all the others
        queue.pop(0)
    return moves

for n in [10, 100, 1000]:
    print(f"emptying a queue of {n:>4} with pop(0): {dequeue_cost(n):>6} element moves")
emptying a queue of   10 with pop(0):     45 element moves
emptying a queue of  100 with pop(0):   4950 element moves
emptying a queue of 1000 with pop(0): 499500 element moves

Emptying the queue costs O(n²) moves in total. The fix is a structure with cheap removal at the front.

The right way: collections.deque

python · try it yourself
from collections import deque

line = deque()
for name in ["Ana", "Ben", "Cleo"]:
    line.append(name)                 # enqueue at the back
print("served:", line.popleft())      # dequeue from the front
print("next up:", line[0])            # peek
line.append("Dev")
print("served:", line.popleft())
print("served:", line.popleft())
print("still waiting:", list(line))
served: Ana
next up: Ben
served: Ben
served: Cleo
still waiting: ['Dev']

The same operations as the animation, with the same results: Ana, Ben and Cleo are served in arrival order and Dev is left.

A queue as a linked list

A linked list with both a head (front) and a tail (back) pointer gives O(1) at both ends: enqueue links a node after the tail, dequeue removes the head.

python · try it yourself
class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

class LinkedQueue:
    def __init__(self):
        self.head = self.tail = None
        self.size = 0

    def enqueue(self, value):
        node = Node(value)
        if self.tail is None:
            self.head = self.tail = node
        else:
            self.tail.next = node
            self.tail = node
        self.size += 1

    def dequeue(self):
        if self.head is None:
            raise IndexError("dequeue from an empty queue")
        value = self.head.value
        self.head = self.head.next
        if self.head is None:          # the queue became empty
            self.tail = None
        self.size -= 1
        return value

q = LinkedQueue()
for job in ["print report", "scan photo", "print label"]:
    q.enqueue(job)
while q.size:
    print("processing:", q.dequeue())
processing: print report
processing: scan photo
processing: print label

Note: Forgetting to reset tail when the last item is dequeued is a classic bug: the next enqueue would attach to a node that is no longer in the queue.

A circular buffer

When the maximum size is known, a fixed array with a moving front index and wrap-around (% capacity) is the fastest queue of all. This is how keyboard buffers and audio streams work:

python · try it yourself
class RingQueue:
    def __init__(self, capacity):
        self.buf = [None] * capacity
        self.front = 0
        self.count = 0

    def enqueue(self, x):
        if self.count == len(self.buf):
            raise OverflowError("queue is full")
        self.buf[(self.front + self.count) % len(self.buf)] = x
        self.count += 1

    def dequeue(self):
        x = self.buf[self.front]
        self.buf[self.front] = None
        self.front = (self.front + 1) % len(self.buf)
        self.count -= 1
        return x

r = RingQueue(3)
r.enqueue("a"); r.enqueue("b"); r.enqueue("c")
print(r.dequeue(), r.buf)
r.enqueue("d")                     # wraps around into slot 0
print(r.buf, "front at", r.front)
try:
    r.enqueue("e")
except OverflowError as err:
    print("error:", err)
a [None, 'b', 'c']
['d', 'b', 'c'] front at 1
error: queue is full

Where queues appear

  • Task scheduling: print jobs, web requests, messages between services.
  • Breadth-first search: explore a graph level by level (Graph Traversal lesson).
  • Buffers: keyboard input, network packets, video streaming.
  • Priority queues are a variation where the most important item leaves first; they are built from heaps (Heaps & Priority Queues lesson).

Test yourself

You enqueue 1, 2, 3 and then dequeue once. What is at the front?

  1. 1
  2. 2
  3. 3
  4. Nothing

Why is list.pop(0) a poor dequeue operation?

  1. It returns the wrong item
  2. It shifts all remaining elements, costing O(n)
  3. It raises an error on lists
  4. It is not allowed in Python

Which traversal algorithm is built on a queue?

  1. Depth-first search
  2. Breadth-first search
  3. In-order traversal
  4. Binary search