Circular Linked List
DSA · Linked Lists
Theory
In a circular linked list the last node points back to the first instead of to None, so traversal can continue around the loop forever. A pointer to any node gives access to the whole list. You must stop traversal when you return to the starting node to avoid an infinite loop.
Why we use it
It naturally models things that repeat in a cycle.
When to use it
Use it for round-robin scheduling, rotating turns in a game, and circular buffers.
How it works
- Start at head
- Visit node
- current = current.next
- current == head? Yes: Full circle: stop. No: Continue visiting.
- Done
Syntax
tail.next = head
Traverse:
cur = head
do:
visit(cur); cur = cur.next
while cur is not headExample
class Node:
def __init__(self, val):
self.val = val
self.next = None
players = [Node(n) for n in ["Asha", "Ravi", "Neha"]]
for i in range(len(players)):
players[i].next = players[(i + 1) % len(players)]
turn = players[0]
for round_no in range(1, 7):
print("Turn", round_no, ":", turn.val)
turn = turn.nextKey points
- Last node links back to the first
- Stop when you reach the start again
- Good for round-robin cycles
- Any node can act as the entry point