Sub topic 9
Queues: FIFO, Enqueue, Dequeue, and Pointer Handling
Prerequisites and the FIFO model
This chapter assumes that you know loops, object references or pointers, and introductory Big-O notation.
A queue is a data structure in which the first item inserted is the first item removed. This rule is called FIFO, or first in, first out. A queue is like a line of people: new people join at the back, and service happens at the front.
The two basic operations are:
- Enqueue: add an item at the rear of the queue.
- Dequeue: remove and return the item at the front.
A queue usually keeps references named front and rear. The front reference identifies the next item to remove. The rear reference identifies where the next item will be added.
Linked-list implementation
A linked queue stores each item in a node. Each node contains data and a reference to the next node. Maintaining both front and rear makes insertion and removal constant-time operations.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedQueue:
def __init__(self):
self.front = None
self.rear = None
def enqueue(self, data):
node = Node(data)
if self.rear is None: # The queue is empty.
self.front = self.rear = node
else:
self.rear.next = node
self.rear = node
def dequeue(self):
if self.front is None:
raise IndexError("dequeue from empty queue")
data = self.front.data
self.front = self.front.next
if self.front is None: # The removed node was the last one.
self.rear = None
return data
q = LinkedQueue()
q.enqueue("A")
q.enqueue("B")
print(q.dequeue()) # A
print(q.dequeue()) # BThe final condition in dequeue is essential. If removing an item makes the queue empty, rear must also become None. Otherwise, rear would point to a node that is no longer in the queue.
Array implementation and operation costs
An array queue can store items in consecutive positions. A naïve dequeue shifts every remaining item toward index zero, which takes O(n) time. A better implementation advances a front index, but a bounded array then needs wrap-around logic to reuse vacant positions. That design is a circular queue, covered separately.
| Operation | Linked queue | Array with shifting |
|---|---|---|
| Enqueue | O(1) | O(1) at the rear |
| Dequeue | O(1) | O(n) |
| Access the front item | O(1) | O(1) |
| Extra space per item | O(1) | O(1) |
GATE problem pattern
When a question asks for strict arrival order, use FIFO reasoning. Track the front and rear separately, and check the empty transition after every dequeue. If a queue implementation claims O(1) dequeue on an array, look for a moving front index or circular indexing rather than repeated shifting.
Exercise
A linked queue contains one node. After one dequeue operation, what should both front and rear contain?
Show answer
Both should be None. The queue is empty, so neither reference may point to the removed node.