Mental Model
We look at each item in the list one by one until we find the value or reach the end.
Analogy: Like checking each book on a shelf from left to right to find a specific title.
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 Result: true (value found)
class Node { constructor(value) { this.value = value; this.next = null; } } class LinkedList { constructor() { this.head = null; } append(value) { const newNode = new Node(value); if (!this.head) { this.head = newNode; return; } let curr = this.head; while (curr.next) { curr = curr.next; // advance curr to next node } curr.next = newNode; // link new node at the end } search(value) { let curr = this.head; while (curr) { if (curr.value === value) { return true; // found the value } curr = curr.next; // move to next node } return false; // value not found } } // Driver code const list = new LinkedList(); list.append(1); list.append(2); list.append(3); const searchValue = 2; console.log(list.search(searchValue));
while (curr) {if (curr.value === value) {curr = curr.next;while (curr) {if (curr.value === value) {return false; // value not found
head is the first node?head to current lets us start from the first node and move forward.class Node {
constructor(value) {
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, target) {
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, target) {
let current = head;
while (current.next !== null) {
if (current.value === target) {
return true;
}
current = current.next;
}
return false;
}current.next !== null, so it stops before the last node.Pass the test and this pattern moves unknown