What is Circular Linked List: Definition and Examples
circular linked list is a type of linked list where the last node points back to the first node, forming a circle. This means you can traverse the list starting from any node and eventually return to it without hitting a null end.How It Works
A circular linked list is like a necklace where each bead (node) is connected to the next, and the last bead connects back to the first one. This creates a loop, so if you keep moving from one bead to the next, you will circle around endlessly.
In a normal linked list, the last node points to null, which means the list ends there. But in a circular linked list, the last node points back to the first node, so there is no end. This allows continuous traversal without stopping.
This structure is useful when you want to cycle through items repeatedly, like players taking turns in a game or a playlist that repeats songs.
Example
This example shows how to create a simple circular linked list with three nodes and traverse it to print all values once.
class Node: def __init__(self, data): self.data = data self.next = None class CircularLinkedList: def __init__(self): self.head = None def append(self, data): new_node = Node(data) if not self.head: self.head = new_node new_node.next = self.head else: temp = self.head while temp.next != self.head: temp = temp.next temp.next = new_node new_node.next = self.head def traverse(self): if not self.head: return temp = self.head while True: print(temp.data, end=' ') temp = temp.next if temp == self.head: break cll = CircularLinkedList() cll.append(10) cll.append(20) cll.append(30) cll.traverse()
When to Use
Circular linked lists are useful when you need to repeatedly cycle through a list without restarting manually. For example:
- In multiplayer games to cycle through players' turns continuously.
- In music or video playlists that loop automatically.
- In scheduling algorithms where tasks are repeated in a round-robin fashion.
This structure helps avoid checking for the end of the list and simplifies continuous looping.
Key Points
- A circular linked list connects the last node back to the first node, forming a loop.
- It allows infinite traversal without a null end.
- Useful for applications requiring repeated cycling through elements.
- Traversal must be carefully controlled to avoid infinite loops.