Find length of linked list (Recursive) Python
Here we will learn how to find the length of the linked list using recursion in Python.
Out of the basic two ways, we will take a look at the recursive way to find the length of the linked list. The other method is to find it iteratively.
In the recursive method instead of keeping a count variable, we keep incrementing the value of the recursion result by ‘1’ and return ‘0’ if the list is empty that is the head of the linked list is pointing to the ‘None’.
Find the length of the linked list using Recursion
So to find the length of a linked list we first need to define the linked list and get elements from the user. Below is our given Python program:
class Node: def __init__(self, data): self.data = data self.next = None def takingInput(): head = tail = None list1 = [int(i) for i in input().split()] for i in list1: if i == -1: break NewNode = Node(i) if head == None: head = NewNode tail = NewNode else: tail.next = NewNode tail = NewNode return head def LengthofLL(head): if head == None: return 0 return 1 + LengthofLL(head.next) Head = takingInput() length = LengthofLL(Head) print(length)
Output:
1 2 2 3 4 4 5 -1 –> linked list
7 –> length of linked list
So here we have defined a Node class which will be used to define nodes of the linked list.
Then we have defined a takingInput()
function which will help us in taking input for the linked list and will accept the input until ‘-1’ is entered
Now for calculating the length of the linked list we have defined a function LengthofLL which will take one argument that is the head of the linked list and if at any moment that head is equal to None the function will return ‘0’. Otherwise will return 1 + the recursive result of the function which is called each time with the next of head.
In the end, we will print the length of the linked list.
Therefore we have learned how to find the length of the linked list recursively in Python.
Leave a Reply