Count Total Nodes in Circular Linked Lists

Sentences that can be formed from the list of words

JAVA Program to Count the Number of Nodes in a Circular Linked List

In this page, we’ll take a look at a program to count the number of nodes in a  circular linked list, a loop is required until the very first element reappears. Circular linked lists have a head and tail. The head marks the beginning of the list pointing towards the first first element whereas the tail is the last element that also points to the first element of the list. A loop iterates through the entire list and increases the value of a counter variable for every passing node. 

Steps to be followed to create a program to count the number of Nodes in a Linked List

To count the number of elements in a circular linked list –

  • Intiate a count variable with zero 
  • Store the value of head in current variable.
  • Iterate through the loop increasing the value of count by 1 and changing the value of current to the next node.
  • Stop the iteration as soon as the current value equals to the head.
  • Print the count variable as the total number of elements in the circular linked list.

Algorithm for writing the function to count Nodes in a Circular Linked List

  • countNodes()
  • Node temp = head
  • do while(temp != head)
    • cnt++
    • temp = temp->next
Run
public class Main {             
    public static void main(String[] args) {  
        Main Obj = new Main();  
        Obj.add(10); 
        Obj.add(20);  
        Obj.add(30);
        Obj.add(40);
        Obj.countNodes();
        } 
    public class Node{  
        int element;  
        Node next; 
        
        public Node(int element) {  
            this.element = element;  
        }  
    } 
    static int cnt;
    public Node head = null;  
    public Node tail = null;
    public void add(int element){  
        Node newNode = new Node(element);  
        if(head == null) {  
            head = newNode;  
            tail = newNode;  
            newNode.next = head;  
            }  
        else {  
            tail.next = newNode; 
            tail = newNode;  
            tail.next = head;  
        }  
    }
    public void countNodes() {  
            Node temp = head;  
            do{ 
                cnt++;  
                temp = temp.next;  
            }while(temp != head);  
            System.out.println("Number of Nodes in the list is "+cnt);  
        }  
}
Number of Nodes in the list is 4