Sub topic 11
Circular linked lists
A circular linked list is a linked list whose last node points back to the first node instead of to None. This chapter assumes you know the singly linked list from earlier chapters: Node with value and next, traversal, insertion, and deletion. It also assumes you can read the Python used here.
What changes when the list closes into a ring
In a singly linked list, the last node's next is None, and every loop you wrote stops when it sees None. In a circular list there is no None in the chain. Following next from any node eventually returns to that node.
The diagram shows a three-node ring. The list object keeps a reference to the last node, called the tail, and the head is always tail.next.
Three consequences follow from this shape:
- No node has a
nextofNone, so a loop written aswhile current is not Nonenever ends. - A one-node list points to itself:
node.next is node. - An empty list is the only case where a reference is
None. Here it is the list'stail.
Why keep the tail instead of the head
You could store a head reference, as in the singly linked list. Then reaching the last node takes O(n), because you walk the whole ring. If you store the tail instead, you get both ends for free:
- The tail is
self.tail. - The head is
self.tail.next.
Inserting at the front and at the back are both O(1), and so is removing the front. This is why circular lists are often used to build queues without a separate head and tail pair.
| Operation | Cost with a tail reference | Reason |
|---|---|---|
| Access the head | O(1) | `tail.next` |
| Insert at the front | O(1) | Link a new node after the tail |
| Insert at the back | O(1) | Insert at the front, then advance the tail |
| Remove the front | O(1) | `tail.next = head.next` |
| Remove the back | O(n) | You need the node before the tail |
| Search for a value | O(n) | Walk at most one full lap |
| Rotate by one | O(1) | Move the tail reference forward |
Implementing the ring
The main difficulty is the termination condition. Instead of stopping at None, you stop when you get back to where you started. Because the loop body must run at least once for a non-empty list, the code uses a while True loop with an exit check. This is Python's version of a do-while loop.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class CircularList:
def __init__(self):
self.tail = None # tail.next is the head
def is_empty(self):
return self.tail is 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 # the new node becomes the tail
def pop_front(self):
if self.tail is None:
raise IndexError("pop from empty list")
head = self.tail.next
if head is self.tail:
self.tail = None
else:
self.tail.next = head.next
return head.value
def rotate(self):
if self.tail is not None:
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:
return
current = current.next
def delete_value(self, value):
if self.tail is None:
return False
prev = self.tail
current = self.tail.next
while True:
if current.value == value:
if current is prev: # the only node in the ring
self.tail = None
else:
prev.next = current.next
if current is self.tail:
self.tail = prev
return True
if current is self.tail:
return False
prev = current
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]
ring.delete_value(3) # removes the tail, so the tail moves back
ring.append(4)
print(list(ring)) # [0, 1, 2, 4]
ring.rotate()
print(list(ring)) # [1, 2, 4, 0]How `push_front` and `append` share code
When the list is empty, the new node points to itself and becomes the tail. When it is not empty, the new node is linked in between the tail and the old head, so the tail's next now names the new head. For append, the same insertion is done, and then the tail reference moves one step forward to the new node. The ring is unchanged. Only the label "this is where the list ends" moves.
Deleting without breaking the ring
delete_value starts with prev at the tail and current at the head. That pairing is deliberate: prev is always the node before current in the ring, even for the head. So the head needs no special case for relinking.
Three situations still need care:
- The only node is deleted. Here
current is prev, and the list becomes empty by settingtail = None. - The tail is deleted. The ring is relinked, and
tailmust move toprev. If you forget this,tailpoints at a node that is no longer in the list. - The value is not found. The loop stops after one lap, when
currentis the tail.
Rotation and the Josephus problem
Moving the tail reference forward by one makes the old head the new tail. This is a rotation, and it costs O(1) because no node is touched. On an array, the same rotation moves every element.
A classic use is the Josephus problem. People stand in a circle, and every k-th person is eliminated until none remain. The ring models this directly: rotate k−1 times to bring the next victim to the front, then pop the front.
# Uses the CircularList class defined above.
def josephus(n, k):
ring = CircularList()
for person in range(1, n + 1):
ring.append(person)
order = []
while not ring.is_empty():
for _ in range(k - 1):
ring.rotate()
order.append(ring.pop_front())
return order
print(josephus(7, 3)) # [3, 6, 2, 7, 5, 1, 4]Each elimination costs O(k), so the whole run is O(n·k). Rotation never copies data, and pop_front keeps the ring closed.
Pitfalls and edge cases
- Empty list.
tailisNone, so every method must check it before readingtail.next. ReadingNone.nextraisesAttributeError. - Single node.
tail.next is tail. Code that assumeshead.nextis a different node breaks here. Inpop_front, the checkhead is self.tailhandles this case. - Forgetting to move the tail. After inserting at the back or deleting the last node, the tail must be updated. If it isn't, the list still iterates, but
appendlinks nodes into the wrong place. - Accidental rings in a plain list. If a bug links a node back to an earlier node in a singly linked list, normal traversal loops forever. The slow and fast pointer technique from the next chapter detects this. On a deliberate circular list, the same technique would always report a cycle, so it only tells you something when the list is supposed to end.
- Counting length. A ring has no end marker, so
lenrequires one full lap, O(n). Keep a size counter if you need it often.
When to use a circular list
Use a circular list when the data is naturally cyclic or when you need cheap access to both ends. Typical cases are round-robin scheduling, where each task gets a turn and then goes to the back, and a buffer of items you cycle through repeatedly, such as a playlist set to repeat. If you do not need to wrap around, a plain singly linked list with a tail reference gives the same O(1) bounds, and its loops end at None, which is simpler to get right.
Exercise
In the CircularList above, delete_value is called on a list holding 5, 6, 7 (tail is 7) with the value 7. Which references change, and what does list(ring) return afterward?
Show answer
Starting with prev at 7 and current at 5, the loop moves along until current is 7 and prev is 6. The value matches, and current is not prev, so prev.next = current.next sets 6's next to 5. Because current is the tail, self.tail is set to prev, which is 6. The result is [5, 6], and 6 is now the tail.
Exercise
Write a method length(self) for CircularList that returns the number of nodes without using a counter attribute. State its time complexity and the one edge case it must handle first.
Show answer
Return 0 if self.tail is None. Otherwise count nodes from self.tail.next until you reach the tail:
def length(self):
if self.tail is None:
return 0
count = 1
current = self.tail.next
while current is not self.tail:
count += 1
current = current.next
return count
It takes O(n) time because it walks one full lap. The empty-list check comes first because self.tail.next would fail on None. A single-node list returns 1, since tail.next is already the tail.