Learn Programming and technology with ease @ developerpublish.com

HomePythonPython Program Find the Length of Linked List using Recursion

# Python Program Find the Length of Linked List using Recursion

In this Python program, we will use recursion to find the length of a linked list. A linked list is a data structure consisting of nodes where each node contains data and a reference (or pointer) to the next node in the sequence.

## Problem statement

Given a linked list, we need to calculate the length of the linked list using recursion.

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

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

def __init__(self):

def append(self, data):
new_node = Node(data)
return
while current.next:
current = current.next
current.next = new_node

def length_recursive(self, node):
if node is None:
return 0
return 1 + self.length_recursive(node.next)

def get_length(self):
llist.append(10)
llist.append(20)
llist.append(30)
llist.append(40)

print("Length of the linked list:", llist.get_length())
```

## How it works

1. We define a `Node` class to represent individual nodes of the linked list. Each node contains data and a reference to the next node.
2. We define a `LinkedList` class with methods to append nodes and find the length of the linked list.
3. The `length_recursive` method takes a node as an argument and recursively calculates the length of the linked list starting from that node.
4. In the `get_length` method, we initiate the recursive length calculation from the head node of the linked list.
5. We create a linked list using the `LinkedList` class and append some nodes to it.
6. Finally, we call the `get_length` method to calculate and print the length of the linked list.

## Input / Output

### You May Also Like

#### Python Program to Remove Duplicates from a Linked List

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...

#### Python Program to Solve the Celebrity Problem

This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...

#### Python Program to Solve n-Queen Problem with Recursion

This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...