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
Other Posts You May Like
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); } }
- How to Find the Length of a Linked List
- Implement Stack using Array
- Implement Stack using Linked List
- Implement Queue using Array
- Implement Queue using Linked List
Comments
Post a Comment