Count the number of nodes in a circular linked list ?

By | July 12, 2020

In this post, We will learn How to write a Java program to count the number of nodes in a circular linked list

Problem Statement in another word:

Check Whether the given LinkedList is NULL terminated. If there is a Cycle/Loop then Find the Length of the Loop.

For Below given diagram Answer would be 4

This problem is the extension of  How to check whether a linked list has a loop/cycle in java ?  After  finding the loop in the LinkedList, keep the fastReference as it is.  the slowReference keeps on moving until it again comes back to  fastReference . While moving slowReference , use a counter variable which increments at the rate of 1.

Complete Source is given Below:

Node.java

 

LinkedList.java

 

ClientTest.java

Output Of this Program:

Total Number of Cicular Nodes:4
————————————————————-
Total Number of Cicular Nodes:6

You May Also Like:

Implementing a Circular Singly Linked List in Java ?
How to check whether a linked list has a loop/cycle in java ?
Find start node of loop in Singly LinkedList in java

That’s all about the Count the number of nodes in a circular linked list?
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published.