Learn Programming and technology with ease @ developerpublish.com

HomePythonPython Program to Search an Element in a Linked List using Recursion

# Python Program to Search an Element in a Linked List using Recursion

In this Python program, we will implement a recursive approach to search for an element in a linked list. A linked list is a data structure where each element (node) contains a value and a reference to the next element in the list. Weâ€™ll define a class for the linked list, and then implement a recursive function to search for a given element within the list.

## Problem Statement

In this Python program, we will implement a recursive approach to search for an element in a linked list. A linked list is a data structure where each element (node) contains a value and a reference to the next element in the list. Weâ€™ll define a class for the linked list, and then implement a recursive function to search for a given element within the list.

## Python Program to Search an Element in a Linked List using Recursion

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

def __init__(self):

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

def search_recursive(self, current, target):

if current is None:
return False
if current.value == target:
return True
return self.search_recursive(current.next, target)

def search(self, target):

search_element = 20

print(f"Element {search_element} found in the linked list.")
else:
```

## How it works

1. The program defines a `Node` class to represent the elements in the linked list.
2. It defines a `LinkedList` class with methods to append elements to the end of the linked list and to search for an element using recursion.
3. The `search_recursive` method is a recursive function that takes a current node and the target element as parameters. It returns `True` if the target element is found, otherwise, it recursively calls itself with the next node.
4. The `search` method initiates the search by calling the `search_recursive` method with the head of the linked list.
5. The program creates a linked list, appends elements, and then searches for a specific target element using the `search` method.
6. The result of the search is printed to the console.

## 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...