How to Find the Length of a Linked List - The Coding Shala

Home >> Data Structures >> Find the Length of a Linked List

 In this post, we will learn how to find the length of a given linked list in Java.

How to Find the Length of a Linked List

You have given a singly linked list, write a Java program to count the number of elements or length of the linked list.

Example 1:
LinkedList: 1->2->3->4->5
Output: 5

Example 2:
LinkedList: 2->4->6->7->5->1->0
Output: 7

Approach 1

Traverse the linked list until you reached the null node.

Java Program: 

/*
class Node{
    int data;
    Node next;
    Node(int a){  
        data = a; 
        next = null; 
    }
}*/

class Solution
{
    public static int getCount(Node head)
    {
        int count = 0;
        Node curr = head;
        while (curr != null) {
            count++;
            curr = curr.next;
        }
        
        return count;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Goal Parser Interpretation LeetCode Solution - The Coding Shala

Check If N and Its Double Exist in an array - The Coding Shala