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 -> [curr->1] -> 2 -> 3 -> null
head -> 1 -> [curr->2] -> 3 -> null
head -> 1 -> [curr->2] -> 3 -> null
head -> 1 -> [curr->2] -> 3 -> null Value 2 found in the list
class ListNode { value: number; next: ListNode | null; constructor(value: number) { this.value = value; this.next = null; } } function searchLinkedList(head: ListNode | null, target: number): boolean { let curr = head; while (curr !== null) { if (curr.value === target) { return true; // found the target value } curr = curr.next; // move to next node } return false; // reached end without finding } // Driver code const head = new ListNode(1); head.next = new ListNode(2); head.next.next = new ListNode(3); const target = 2; const found = searchLinkedList(head, target); console.log(found ? `Value ${target} found in the list` : `Value ${target} not found in the list`);
while (curr !== null) {if (curr.value === target) {return true; // found the target valuecurr = curr.next; // move to next nodereturn false; // reached end without findingwhile (curr !== null) {if (curr.value === target) {return false; // reached end without findingclass Node {
value: number;
next: Node | null;
constructor(value: number) {
this.value = value;
this.next = null;
}
}
const head = new Node(5);
head.next = new Node(10);
head.next.next = new Node(15);
function search(head: Node | null, target: number): boolean {
let current = head;
while (current !== null) {
if (current.value === target) return true;
current = current.next;
}
return false;
}
console.log(search(head, 10));
console.log(search(head, 20));function search(head: Node | null, target: number): boolean {
let current = head;
while (current.next !== null) {
if (current.value === target) return true;
current = current.next;
}
return false;
}function countOccurrences(head: Node | null, target: number): number {
// Your code here
}Pass the test and this pattern moves unknown