Guided Project: Introduction to Recursion

Learn how to implement recursive functions to solve problems with linked lists and other recursive data structures.

Recursive Linked List Search

Example Implementation

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); } }

Example Usage:

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

Practice Problems

To further enhance your recursion skills, try these LeetCode problems:

Linked List Recursion Problems

Basic Recursion Problems

Advanced Recursion Problems