Sub topic 9
Queues: FIFO, Enqueue, Dequeue, and Pointer Handling
This chapter assumes you know arrays and indexing, singly linked lists, and introductory Big-O. It also assumes you can read short Python programs. Circular queues get their own chapter, so here we only show why they are needed.
The queue ADT
A queue is an abstract data type (ADT) that removes elements in the order they arrived. This rule is called FIFO (first in, first out). Insertion happens at one end, the rear (also called the tail). Removal happens at the other end, the front (also called the head).
The core operations are:
enqueue(x)addsxat the rear.dequeue()removes and returns the front element.peek()(orfront()) returns the front element without removing it.is_empty()andis_full()report the state. A linked queue is never full, except when memory runs out.
Two error conditions matter in exam questions:
- Overflow: you call
enqueueon a full bounded queue. - Underflow: you call
dequeueon an empty queue.
Unlike a stack, a queue touches both ends, so you must keep track of two positions. Most queue bugs come from updating one of them incorrectly.
Array implementation with front and rear
The simplest design uses a fixed-size array and two indices. Here front is the index of the first element and rear is the index of the last element. An empty queue has rear = front - 1.
class ArrayQueue:
def __init__(self, capacity):
self.a = [None] * capacity
self.front = 0
self.rear = -1
def is_empty(self):
return self.rear < self.front
def is_full(self):
return self.rear == len(self.a) - 1
def enqueue(self, x):
if self.is_full():
raise OverflowError('queue full')
self.rear += 1
self.a[self.rear] = x
def dequeue(self):
if self.is_empty():
raise IndexError('queue empty')
x = self.a[self.front]
self.front += 1
return x
q = ArrayQueue(3)
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
print(q.dequeue()) # 1
print(q.is_full()) # True, although one slot is freeBoth operations take O(1) time. The design has one flaw. After the dequeue above, slot 0 is free, but rear is still 2, so is_full() reports true. This is false overflow: the queue claims to be full while space remains at the start of the array.
There are two fixes:
- Shift every element left on each dequeue. This keeps the indices simple but makes dequeue O(n).
- Let the indices wrap around the end of the array. This is the circular queue, which keeps both operations at O(1).
Linked list implementation
A linked queue uses a singly linked list with two pointers. Dequeue removes at the head, and enqueue adds at the tail. This direction is deliberate. Removing at the head takes O(1) in a singly linked list. Removing at the tail would take O(n), because you would have to walk the list to find the node before it, since a singly linked list has no backward pointer.
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class LinkedQueue:
def __init__(self):
self.head = None
self.tail = None
def is_empty(self):
return self.head is None
def enqueue(self, x):
node = Node(x)
if self.tail is None: # queue was empty
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail = node
def dequeue(self):
if self.head is None:
raise IndexError('queue empty')
x = self.head.data
self.head = self.head.next
if self.head is None: # queue became empty
self.tail = None
return x
q = LinkedQueue()
for v in (10, 20, 30):
q.enqueue(v)
print(q.dequeue(), q.dequeue()) # 10 20
print(q.dequeue()) # 30
print(q.is_empty()) # TruePointer handling and edge cases
The two guarded if statements in the code above are the main source of errors.
- Enqueue on an empty queue: both
headandtailmust point to the new node. If you only settail.next, you crash onNone. - Dequeue of the last element:
headbecomesNone, sotailmust also be reset toNone. If you forget this,tailkeeps pointing to a removed node. The next enqueue then attaches the new node to that dead node, and the queue looks empty even though it holds data. - Order of the two enqueue assignments: link the old tail to the new node first, then move
tail. Reversing the order loses the old tail.
Some implementations store only a tail pointer in a circular linked list. In that design the head is tail.next, and both operations stay O(1).
Cost comparison
| Operation | Array queue (linear) | Array queue (shift on dequeue) | Linked queue (head and tail) |
|---|---|---|---|
| enqueue | O(1) | O(1) | O(1) |
| dequeue | O(1) | O(n) | O(1) |
| peek | O(1) | O(1) | O(1) |
| Wasted space | Yes, false overflow | No | None, but one pointer per node |
| Capacity | Fixed | Fixed | Limited only by memory |
A linked queue without a tail pointer makes enqueue O(n), because you must walk to the last node. GATE questions often test this by asking which pointers are kept.
Common GATE patterns
Most exam questions on this topic reduce to one of these tasks.
- Trace a sequence of enqueues and dequeues and report the final contents or the value returned by a particular dequeue. Apply FIFO exactly.
- Choose pointers for a linked queue. Ask which operations need O(1) and which pointer each one touches. Head and tail together give O(1) for both operations.
- Count false overflow. Given a linear array queue, find how many enqueues succeed before the queue reports full, given a mix of dequeues in between. The answer depends only on
rear, never on how many elements are currently stored. - Detect the empty-and-full ambiguity. In circular layouts,
front == rearcan mean either state. The next chapter shows how to resolve it. - Find the number of elements. In a linear array queue it is
rear - front + 1, using the convention above.
A queue also appears inside larger algorithms. Breadth-first search uses a queue to process vertices level by level, and operating systems use queues for ready processes and printer jobs. These uses all depend on the FIFO rule.
Exercise
A linked queue keeps only a head pointer and no tail pointer. Each node has a next field. What is the worst-case time of enqueue and of dequeue? How does adding a tail pointer change the cost? What extra step must dequeue perform once the tail pointer exists?
Show answer
Without a tail pointer, enqueue must walk from head to the last node, so it takes O(n). Dequeue only changes head, so it takes O(1). With a tail pointer, enqueue becomes O(1) because it links the new node after tail and then moves tail. Dequeue stays O(1), but when the removal empties the queue (head becomes None), dequeue must also set tail to None. Otherwise tail points to a removed node.
Exercise
A linear array queue has capacity 5, with front = 0 and rear = -1 at the start. It performs these operations in order: enqueue 4 items, dequeue 3 items, enqueue 2 items. How many of the enqueues fail, and what is the state at the end?
Show answer
The first 4 enqueues put items in slots 0 to 3, so rear = 3. The 3 dequeues move front to 3. The first of the last two enqueues goes into slot 4, so rear = 4. The second fails with overflow, because rear == capacity - 1, although slots 0 to 2 are free. So exactly 1 enqueue fails. The final state is front = 3, rear = 4, and the queue holds 2 elements.