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) {
            curr =;
        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.


Popular Posts from this Blog

LeetCode - Crawler Log Folder Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

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

First Unique Character in a String Java - The Coding Shala

Add two numbers in Scala - The Coding Shala