Sub topic 11
Circular linked lists
This chapter assumes you can build and traverse a singly linked list, as in the earlier chapters. You should also know that head is the entry point and that None marks the end of a chain.
What changes in a circular list
A circular linked list is a linked list where the last node's next points back to the first node instead of None. No node has a next of None (except in the empty list), so the chain forms a ring.
The node class is the same as before. Only the wiring and the stopping rule differ.
Keep a tail reference
A singly linked list with only a head needs O(n) time to append, because you walk to the last node. In a circular list, the head is always tail.next. So you can store just the tail and reach both ends in O(1).
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class CircularList:
def __init__(self):
self.tail = None
def push_front(self, value):
node = Node(value)
if self.tail is None:
node.next = node
self.tail = node
else:
node.next = self.tail.next
self.tail.next = node
def append(self, value):
self.push_front(value)
self.tail = self.tail.next
def __iter__(self):
if self.tail is None:
return
current = self.tail.next
while True:
yield current.value
if current is self.tail:
break
current = current.next
ring = CircularList()
for v in (1, 2, 3):
ring.append(v)
ring.push_front(0)
print(list(ring)) # [0, 1, 2, 3]Both operations are O(1). A single node in an empty list points to itself, and append is push_front followed by moving the tail forward one step.
Traversal needs a new stopping rule
The usual loop, while current is not None, never ends on a circular list. Two safe patterns exist:
- Stop when you return to the node where you started. The
__iter__above stops atself.tail, which is the last node of the ring. - Count nodes. If you know the length, loop that many times.
Searching uses the same rule. A search that does not find the value must stop after one full lap, or it loops forever.
Deletion and the single-node case
Deleting works like the singly linked version: find the node before the target and make its next skip over the target. Two cases need extra care:
- If the list has one node, deleting it must set
tailtoNone. Otherwisetail.nextstill points at the removed node. - If you delete the tail, the previous node becomes the new tail.
Rotation
Because the list is a ring, rotating it by one position costs O(1). You only move the tail reference:
def rotate(ring):
if ring.tail is not None:
ring.tail = ring.tail.nextAfter rotate, the old head is the new tail, so the old second node becomes the head. A rotation on an array moves every element.
Where they fit
Circular lists suit problems that cycle through items repeatedly:
- Round-robin scheduling, where each task gets a turn and then goes to the back.
- Turn order in a game.
- Buffers that wrap around.
For plain sequences with a start and an end, a singly linked list with a tail reference does the same job with a simpler stopping rule.
Cycles by accident
A circular list is a deliberate cycle. The same shape can also appear by mistake in a list that was meant to end, for example when a bug links the last node back to an earlier one. Such a list hangs any traversal that looks for None. The chapter on cycle detection shows how slow and fast pointers find this shape without extra memory.
Exercise
In a CircularList that stores only tail, how do you get the first value, and what is the cost of the lookup? What must delete do when the list holds exactly one node?
Show answer
The first node is tail.next, so reading its value is O(1). When the list holds exactly one node, deleting it must set tail to None. Otherwise tail and tail.next would still point at the removed node.