Count Nodes in Circular LinkedList

Count Nodes in Circular LinkedList

To calculate the nodes in the circular linked list

  • iterate the list from head with the help of dummy node (copy of reference in code cll) and stop iterating when it reaches to the head of the list.

Here is the code



package com.diaryreaders.datastructures.linkedlist;
public class LengthCircularLinkedList {
public static void main(String[] args) {
CircularLinkedList cll1 = new CircularLinkedList();
CircularLinkedList cll2 = new CircularLinkedList();
CircularLinkedList cll3 = new CircularLinkedList();
CircularLinkedList cll4 = new CircularLinkedList();
CircularLinkedList cll5 = new CircularLinkedList();
cll1.setData(1);
cll2.setData(2);
cll3.setData(3);
cll4.setData(4);
cll5.setData(5);
cll1.setNext(cll2);
cll2.setNext(cll3);
cll3.setNext(cll4);
cll4.setNext(cll5);
cll5.setNext(cll1);
System.out.println("Length of the Circular LinkedList : " + getLength(cll1));
}
private static int getLength(CircularLinkedList head) {
CircularLinkedList cll = head;
int i = 0;
while (cll != null) {
i++;
cll = cll.getNext();
if (head == cll) {
break;
}
}
return i;
}
}

Output:

No Comments Yet

Leave a Reply

Your email address will not be published.

Lorem ipsum dolor sit amet, consectetur a dipiscing elit. Vivamus leo ante,

FOLLOW US ON