Circular Linked List
A circular linked list is like a circular race track. Instead of ending with null, the last node points back to the first node. It can be singly or doubly linked.
Circular linked lists are useful for applications that require cyclic iteration, like round-robin scheduling, or representing a circle of players in a game.
Singly Circular Linked List Implementation
public class CircularLinkedList {
Node head;
// Insert at beginning
public void insertAtHead(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
newNode.next = head; // point to itself
} else {
Node temp = head;
while (temp.next != head) temp = temp.next;
newNode.next = head;
temp.next = newNode;
head = newNode;
}
}
// Insert at end
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;
}
}
// Print list
public void printList() {
if (head == null) return;
Node temp = head;
do {
System.out.print(temp.data + " -> ");
temp = temp.next;
} while (temp != head);
System.out.println("(back to head)");
}
}
Two Minute Drill
- Circular linked list: last node points to first node.
- No null pointers, can be traversed indefinitely.
- Useful for round-robin scheduling, music playlist loops.
- Operations similar to singly linked list but careful with termination condition.
Need more clarification?
Drop us an email at career@quipoinfotech.com
