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