Round trips need a stopping rule.
Model round-robin work and avoid waiting for an end marker that does not exist.
01 Model the idea
A circular list connects its tail back to its head. This can model a repeated rotation, but ordinary traversal-until-None is no longer a valid stopping rule. Stop after a known number of nodes or when the cursor returns to the starting node. Decide what an empty cycle means before dereferencing its head.
Every next link stays within the intended cycle.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
VISIT the current node
ADVANCE through next
STOP after a chosen count or return to starting identity03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
class Node:
def __init__(self, value): self.value, self.next = value, None
a, b, c = Node("A"), Node("B"), Node("C")
a.next, b.next, c.next = b, c, a
current = a
for _ in range(5):
print(current.value)
current = current.nextA B C A B
- 1
The tail has a real next node instead of None. A bounded five-step simulation demonstrates repeated scheduling without creating an infinite loop.
- 2
A full-cycle traversal can stop when current is head again after at least one visit. Comparing node identity avoids confusing duplicate values with the starting node.
- 3
Insertion and removal must preserve the tail-to-head connection. Keep ownership of head and tail explicit rather than reconstructing them by scanning every time.
04 Count the cost
O(k) for k rotation steps
O(n) stored nodes; O(1) traversal state
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Traverse one cycle of three nodes and collect exactly three values.
Reveal one possible solution +
class Node:
def __init__(self, value): self.value, self.next = value, None
a, b, c = Node("A"), Node("B"), Node("C")
a.next, b.next, c.next = b, c, a
result, current = [], a
while True:
result.append(current.value)
current = current.next
if current is a: break
print(result)06 Check your reasoning
Why is while current is not None unsuitable for an intact circular list?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.