Mental Model
We look at each item in the list one by one until we find the value or reach the end.
Analogy: Like flipping through pages of a book to find a specific word, checking each page in order.
head -> [1] -> [2] -> [3] -> null
↑head -> [1] -> [2] -> [3] -> null
↑head -> [1↑] -> 2 -> 3 -> null
head -> 1 -> [2↑] -> 3 -> null
head -> 1 -> [2↑] -> 3 -> null
head -> 1 -> [2↑] -> 3 -> null Found: true
public class LinkedListSearch { static class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } } public static boolean search(Node head, int target) { Node current = head; while (current != null) { if (current.data == target) { return true; // found the target } current = current.next; // move to next node } return false; // target not found } public static void main(String[] args) { Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); int target = 2; boolean found = search(head, target); System.out.println("Found: " + found); } }
Node current = head;while (current != null) {if (current.data == target) {return true; // found the targetcurrent = current.next; // move to next nodereturn false; // target not foundwhile (current != null) {if (current.data == target) {return false; // target not found
target?Node current = head;
boolean found = false;
while(current != null) {
if(current.data == 5) {
found = true;
break;
}
current = current.next;
}
System.out.println(found);Node current = head;
while(current.next != null) {
if(current.data == target) {
System.out.println("Found");
break;
}
current = current.next;
}Pass the test and this pattern moves unknown