...

/

Solution Review: Search for a Value in a Linked List

Solution Review: Search for a Value in a Linked List

This lesson provides a detailed review of the solution to the challenge in the previous lesson.

Solution: Search for a Value in a Linked List

Press + to interact
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. ...