Search⌘ K

Solution Review: Search for a Value in a Linked List

Explore how recursion can be applied to search for a specific value in a linked list. Understand the base case when the list ends, and the recursive case that checks each node's value. This lesson helps you grasp recursive calls, stack behavior, and linked list traversal—all essential for coding interviews.

Solution: Search for a Value in a Linked List

Java
class Solution {
public static boolean search(Node head, int num) {
// Base case
if (head == null) {
return false;
}
// Recursive case
else {
if (head.value == num) {
return true;
}
else {
return search(head.next, num);
}
}
}
public static void main( String args[] ) {
/* Start with the empty list */
LinkedList list = new LinkedList();
list.insertAtHead(0);
list.insertAtHead(3);
list.insertAtHead(1);
list.insertAtHead(6);
list.insertAtHead(4);
System.out.println("Linked List: ");
for (Node i = list.head; i != null; i = i.next) {
System.out.print(i.value + " ");
}
System.out.println(" ");
int searchFor = 8;
boolean result = search(list.head, searchFor);
System.out.println("Is " + searchFor + " present in the list? : " + result);
}
}

Understanding the Code

The code above can be broken down into two parts:recursive method and the main where the method is called.

Driver Method

The driver code is from line 21 to line 37.

  • In the driver code, between lines 22 and 27, a new linked list list is created, and 5 new nodes are added to the list. ...