Sub topic 7
Circular operations and traversing without looping forever
This chapter assumes you know Python classes and generators, how a singly linked list stores a next reference, and Big-O notation. It covers the operations on a circular singly linked list that keeps only a tail reference, and the loop conditions that keep traversal finite.
Why traversal is the main risk
In a normal list the last node has next = None, so while node is not None ends the loop. In a circular list no node has next = None. The same loop never ends, and it runs until you stop the program or run out of memory if the loop body allocates.
A circular traversal needs a different stopping rule. Two common rules work:
- Stop when you return to the node where you started.
- Stop when you reach a known end node, such as the tail.
The code in this chapter uses the second rule.
The tail-only layout
The list stores only tail. The head is always tail.next, so both ends are reachable in O(1) with one reference.
The implementation
class SNode:
def __init__(self, value):
self.value = value
self.next = None
class CircularList:
"""Circular singly linked list that stores only a tail reference."""
def __init__(self):
self.tail = None
def push_front(self, value):
node = SNode(value)
if self.tail is None:
node.next = node
self.tail = node
else:
node.next = self.tail.next
self.tail.next = node
def push_back(self, value):
self.push_front(value)
self.tail = self.tail.next
def rotate(self):
if self.tail is not None:
self.tail = self.tail.next
def __iter__(self):
if self.tail is None:
return
node = self.tail.next
while True:
yield node.value
if node is self.tail:
break
node = node.nextHow each operation works
push_front has two cases. In an empty list, the new node points to itself and becomes the tail. That self-loop is what makes a one-element circular list valid. Otherwise the new node takes the old head as its next, and the tail points to the new node. The tail does not move, so the new node becomes the head.
push_back reuses push_front and then moves the tail forward one step. The new node was inserted just after the tail, so advancing tail to tail.next makes it the new tail. This works for the empty case too, because the single node's next is itself.
rotate moves the tail one step forward, which makes the old head the new tail and the next node the new head. No nodes are created or relinked. This is O(1), and it is the basis of round-robin scheduling.
__iter__ starts at the head and yields values until it has yielded the tail. The check comes after the yield, so the tail's value is included. The loop is while True with an explicit break, because a None check cannot work here.
Using it
ring = CircularList()
for v in ("a", "b", "c"):
ring.push_back(v)
ring.push_front("z")
print(list(ring)) # ['z', 'a', 'b', 'c']
ring.rotate()
print(list(ring)) # ['a', 'b', 'c', 'z']After rotate, the old head z is the tail, so it prints last.
Cost summary
| Operation | Time | Why |
|---|---|---|
| `push_front` | O(1) | Uses `tail.next` as the head |
| `push_back` | O(1) | Insert after the tail, then advance it |
| `rotate` | O(1) | Moves one reference |
| Traverse | O(n) | Visits each node once |
| Remove the tail | O(n) | Needs the predecessor, and there is no `prev` |
Common errors
- Looping on
None.while node:never ends in a circular list. - Checking the stop condition before yielding. This skips the last node.
- Forgetting the single-node case. The first node must point to itself, or the ring is broken.
- Moving the tail in
push_front. The tail must stay put, or the new node becomes the last element instead of the first. - Using
while node is not startwhen the loop starts atstart. The condition is false on the first check, so nothing is visited. Use ado-whileshape (while Truewith abreak), as above.
Exercises
Exercise
In the CircularList above, what does list(ring) return after pushing 1, 2, 3 with push_back, then calling rotate twice?
Show answer
[3, 1, 2]. After push_back of 1, 2, 3, the order is 1, 2, 3 with tail 3. The first rotate makes 1 the tail, so the order is 2, 3, 1. The second rotate makes 2 the tail, so the order is 3, 1, 2.
Exercise
Why does removing the tail node take O(n) in this list, while push_back takes O(1)?
Show answer
To remove the tail you must change the next of its predecessor, and a singly linked node has no prev. You must walk from the head to find the node just before the tail. Insertion after the tail needs no predecessor, so it is constant time.