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

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

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

How to Find the Length of a Linked List using Recursion

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

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

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

Approach 1

If the current node is null then it will be our break condition of recursion.

Java Program: 

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

class Solution
{
    public static int getCount(Node head)
    {
        return findLength(head);
    }
    
    public static int findLength(Node curr) {
        if(curr == null) {
            return 0;
        }
        return 1 + findLength(curr.next);
    }
}


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

LeetCode - Bulb Switcher Solution - The Coding Shala

Anti Diagonals - The Coding Shala

Sorting the Sentence LeetCode Solution - The Coding Shala

Java Method Overloading - The Coding Shala