Learn how to implement recursive functions to solve problems with linked lists and other recursive data structures.
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# Add a node to the end of the list
def append(self, value):
new_node = Node(value)
if not self.head:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node
# Recursive search implementation
def recursive_search(self, value):
return self._recursive_search_helper(self.head, value)
def _recursive_search_helper(self, node, value):
# Base cases
if node is None:
return False
if node.value == value:
return True
# Recursive case
return self._recursive_search_helper(node.next, value)
list_ = LinkedList()
list_.append(1)
list_.append(2)
list_.append(3)
list_.append(4)
print(list_.recursive_search(3)) # True
print(list_.recursive_search(5)) # False
To further enhance your recursion skills, try these LeetCode problems: