
Most linked lists eventually end.
You keep following nodes and finally reach:
null
But what if the list never ended?
What if the last node connected back to the first node?
That's exactly what a Circular Linked List does.
1. What is a Circular Linked List?
A Circular Linked List is a linked list where:
- the last node points back to the first node.
Visual:
[10] → [20] → [30]
↑ ↓
└─────────────┘
Instead of:
30 → null
we have:
30 → head
2. Why Use Circular Linked Lists?
Circular structures are useful whenever operations repeat continuously.
Examples:
- Round Robin CPU Scheduling
- Music Playlist Loops
- Multiplayer Game Turns
- Resource Sharing Systems
3. Insert at Head
Idea
Create a new node and reconnect the last node to the new head.
public void insertAtHead(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
newNode.next = head;
} else {
Node temp = head;
while (temp.next != head)
temp = temp.next;
newNode.next = head;
temp.next = newNode;
head = newNode;
}
}
Special Case
Unlike normal linked lists:
- we must update the last node's next pointer.
Otherwise the circle breaks.
4. Insert at End
Idea
Find the last node and connect it to head.
public void insertAtEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
newNode.next = head;
} else {
Node temp = head;
while (temp.next != head)
temp = temp.next;
temp.next = newNode;
newNode.next = head;
}
}
5. Traversal
Traversal is slightly different.
In a normal linked list:
while(temp != null)
works.
But here:
- null never appears.
So we stop when we return to head.
do {
System.out.print(temp.data);
temp = temp.next;
} while(temp != head);
6. Advantages
- Continuous Traversal
Perfect for cyclic systems.
- No Need to Restart
The next element is always available.
- Great for Scheduling
Round-robin algorithms naturally fit this structure.
7. Drawbacks
- More Care Needed
Traversal conditions become tricky.
- Infinite Loop Risk
Incorrect termination can cause endless loops.
Key Insights
- Last node points to head
- No null at the end
- Traversal uses special stopping conditions
- Excellent for cyclic applications
A Circular Linked List is essentially a Linked List with no finish line.
That simple change makes it perfect for systems that repeat endlessly, such as schedulers, games, and playlists.
Explore More: https://www.quipoin.com/tutorial/data-structure-with-java/circular-linked-list
Top comments (0)