Sub topic 3
Linked-node queues with head and tail pointers
This chapter assumes you know basic Python classes, how a list is indexed, and Big-O notation for common operations. The previous chapter showed that list.pop(0) costs O(n) because every remaining item shifts left. A linked-node queue avoids that shift by never storing items in a contiguous block.
The idea
A linked queue is a chain of small objects called nodes. Each node holds one value and a reference to the next node. The queue keeps two references:
headpoints to the front node, where items leave.tailpoints to the last node, where items arrive.
Enqueue attaches a new node after tail. Dequeue detaches the node at head. Neither operation touches the other nodes, so both take O(1) time.
Why the tail pointer matters
A singly linked list with only a head can remove from the front in O(1), but adding at the back means walking the whole chain to find the last node. That is O(n). Keeping a tail reference makes the back reachable in one step.
The direction of the links matters too. Links point from the front toward the back, so removing the head only needs head.next. If the links pointed the other way, removing the front would require finding the node before it, which means another walk.
Implementation
class _Node:
__slots__ = ("value", "next")
def __init__(self, value):
self.value = value
self.next = None
class LinkedQueue:
def __init__(self):
self._head = None
self._tail = None
self._size = 0
def __len__(self):
return self._size
def enqueue(self, item):
node = _Node(item)
if self._tail is None: # queue is empty
self._head = node
else:
self._tail.next = node
self._tail = node
self._size += 1
def dequeue(self):
if self._head is None:
raise IndexError("dequeue from empty queue")
node = self._head
self._head = node.next
if self._head is None: # queue became empty
self._tail = None
self._size -= 1
return node.value
def peek(self):
if self._head is None:
raise IndexError("peek from empty queue")
return self._head.value
q = LinkedQueue()
for letter in "abc":
q.enqueue(letter)
print(q.dequeue(), q.peek(), len(q)) # a b 2__slots__ stops Python from giving each node a per-instance dictionary, which saves memory when there are many nodes.
The edge cases that cause bugs
Almost every bug in a linked queue comes from the two moments when the queue changes between empty and non-empty.
- Enqueue into an empty queue. Both
headandtailmust point to the new node. If you only settail,dequeueseeshead is Noneand reports an empty queue whilelensays otherwise. - Dequeue the last item. After
headmoves toNone, you must also settailtoNone. If you forget,tailstill points at a removed node. The nextenqueuethen links a new node onto that stale node, and the new node is unreachable fromhead. Items vanish silently. - Dequeue from an empty queue. Raise an error instead of dereferencing
None, which would give a confusingAttributeError.
The code above handles each case with an explicit if branch. When you write your own version, test those three cases first.
Costs and trade-offs
| Operation | Linked queue |
|---|---|
| enqueue | O(1) |
| dequeue | O(1) |
| peek | O(1) |
| size | O(1) with a counter |
| access item k | O(k) |
Every operation at the ends is O(1) in the worst case, with no occasional expensive resize like a growing array. The costs are elsewhere:
- Each node is a separate Python object with its own allocation, so memory use per item is higher than in an array.
- Nodes are scattered in memory, which gives poor cache locality compared with a contiguous buffer.
- There is no fast indexing. Reaching the middle means following links.
Because of this, a hand-written linked queue in Python is mostly a teaching tool. In real code, collections.deque gives the same O(1) end operations with less overhead. Later chapters cover it. The next chapter shows the circular buffer, which gets O(1) operations from a single contiguous array.
Exercise
In the LinkedQueue above, suppose dequeue removed the last item but did not set self._tail = None. You then call enqueue("x") and dequeue(). What happens, and why?
Show answer
enqueue("x") sees that _tail is not None, so it links the new node to the stale old tail instead of setting _head. _head stays None and _size becomes 1. dequeue() then sees _head is None and raises IndexError("dequeue from empty queue") even though len(q) is 1. The item "x" is unreachable from the head.
Exercise
Why does a linked queue link nodes from front to back, so that next points toward the tail, instead of from back to front?
Show answer
Dequeue must find the new front after removing the old one. With front-to-back links, that is head.next, found in O(1). With back-to-front links, a node has no reference to the node ahead of it, so finding the new front requires walking from the tail, which costs O(n).