Learn how to implement recursive functions to solve problems with linked lists and other recursive data structures.
class Node {
int value;
Node next;
Node(int value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
Node head;
public LinkedList() {
this.head = null;
}
// Add a node to the end of the list
public void append(int value) {
Node newNode = new Node(value);
if (head == null) {
head = newNode;
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
// Recursive search implementation
public boolean recursiveSearch(int value) {
return recursiveSearchHelper(head, value);
}
private boolean recursiveSearchHelper(Node node, int value) {
// Base cases
if (node == null) return false;
if (node.value == value) return true;
// Recursive case
return recursiveSearchHelper(node.next, value);
}
}
LinkedList list = new LinkedList();
list.append(1);
list.append(2);
list.append(3);
list.append(4);
System.out.println(list.recursiveSearch(3)); // true
System.out.println(list.recursiveSearch(5)); // false
To further enhance your recursion skills, try these LeetCode problems: