In this article, we will learn how to find the length of a circular linked list. Actually finding length means we will count the total number of nodes present in a linked list.
To count the node, we will traverse the linked list till the end node.
As we know that in a circular linked list, last node doesn't point to NULL instead it points to head; thus, we need to compare with the head pointer and traverse until the current node next is head.
For Example:
As given in the diagram, there are a total 3 nodes, so we can say that the length of a circular linked list is 3.

Example: Find the length of Circular Linked List in Java
// Class representing a node in a circular linked list
class Node {
public int data; // Store value of the node
public Node next; // Store address of the next node
// Constructor to initialize a node
public Node(int data) {
this.data = data;
this.next = null;
}
}
// Java program to find the length of a circular linked list
public class FindLenghInCLL {
// Function to find length of circular linked list
static void findLength(Node head) {
int length = 0;
if (head != null) {
Node node = head;
do {
node = node.next;
length++;
} while (node != head);
}
System.out.println("Length of Circular Linked List is: " + length);
}
public static void main(String[] args) {
// Create a circular linked list
Node head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head.next.next.next.next = new Node(50);
head.next.next.next.next.next = head;
// Find and print the length of a Circular Linked List
findLength(head);
}
}
Length of Circular Linked List is: 5
Time Complexity: O(n), here n represent the total number of nodes in a circular linked list.
Auxiliary Space: O(1)