Search⌘ K
AI Features

Challenge 1: Length of a Linked List

Explore how to determine the length of a linked list through recursion. This lesson guides you to transform iterative code into a recursive method without altering the input parameters. Understand the comparison between recursion and iteration while practicing implementation in Java.

We'll cover the following...

Problem Statement

Given a Linked List, you are required to find the length of the list using recursion.

The illustration below explains the concept.

The iterative code has been provided for you in the code snippet given below.

Java
class Solution {
/* Returns count of nodes in linked list */
public static int lengthOfList(Node head)
{
int count = 0;
Node temp = head;
while (temp != null) {
count++;
temp = temp.next;
}
return count;
}
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));
}
}

Try it Yourself!

Modify the code of the lengthOfList method and then implement the same code recursively. Make sure not to change the input parameters of this method. Try to attempt this challenge by yourself before moving on to the solution. Goodluck!

Java
class Solution {
/* Returns count of nodes in linked list */
public static int lengthOfList(Node head) {
// Write your code here
// Modify the return statement according to your code
return 0;
}
}

Let’s move on to the detailed solution review of this challenge in the next lesson.