Search⌘ K

Solution Review: Length of a Linked List

Explore the step-by-step process of finding the length of a linked list using recursion in Java. Understand how the method updates the head in each recursive call, identify the base case for termination, and visualize how recursion uses the call stack to solve this problem effectively.

Solution: Length of a Linked List

Java
class Solution {
/* Returns count of nodes in linked list */
public static int lengthOfList(Node head)
{
// Base case
if (head == null) {
return 0;
}
// Recursive case
else {
return 1 + lengthOfList(head.next);
}
}
public static void main(String[] args)
{
/* Start with the empty list */
LinkedList llist = new LinkedList();
llist.push(1);
llist.push(3);
llist.push(1);
llist.push(2);
llist.push(1);
System.out.println("Count of nodes is = " + lengthOfList(llist.head));
}
}

Understanding the Code

The code given above can be broken down into two parts. The recursive method and the main where the method is called.

Driver Method

The driver code is from line 17 to line 25.

  • In the driver code, from line 18 to ...