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

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

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

Java Program to Convert Decimal to Binary - The Coding Shala