# Python Program to Find the Length of the Linked List using Recursion

PythonServer Side ProgrammingProgramming

When it is required to find the length of a linked list with the help of recursion, a method to add elements to the linked list, and a method to calculate the length of the linked list is defined. A helper function is defined that is called with the help of the previously defined length calculation method.

Below is a demonstration for the same −

## Example

Live Demo

class Node:
def __init__(self, data):
self.data = data
self.next = None

class my_linked_list:
def __init__(self):
self.head = None
self.last_node = None

def add_value(self, my_data):
if self.last_node is None:
self.head = Node(my_data)
self.last_node = self.head
else:
self.last_node.next = Node(my_data)
self.last_node = self.last_node.next

def calculate_length(self):
return self.length_helper_fun(self.head)

def length_helper_fun(self, curr):
if curr is None:
return 0
return 1 + self.length_helper_fun(curr.next)

my_instance = my_linked_list()
my_data = input('Enter elements of the linked list ').split()
for elem in my_data:
my_instance.add_value(int(elem))
print('The length of the linked list is ' + str(my_instance.calculate_length()))

## Output

Enter elements of the linked list 12 45 32 67 88 0 99
The length of the linked list is 7

## Explanation

• The ‘Node’ class is created.

• Another ‘my_linked_list’ class with required attributes is created.

• It has an ‘init’ function that is used to initialize the first element, i.e the ‘head’ to ‘None’ and last node to ‘None’.

• Another method named ‘add_value’ is defined, that is used to add data to the linked list.

• Another method named ‘calculate_length’ is defined that is used to call the helper function to find the length of the linked list.

• The helper function is defined, since recursion needs to be used here.

• It checks for the current value of node, and returns the length of the list.

• An object of the ‘my_linked_list’ class is created.

• The user input is taken for the elements in the linked list.

• Methods are called on it to add data.

• The calculate_length method is called, and output is displayed on the console.

Published on 14-Apr-2021 13:04:35
Advertisements