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; value 2 found
package main import "fmt" type Node struct { value int next *Node } func search(head *Node, target int) bool { curr := head for curr != nil { if curr.value == target { return true } curr = curr.next } return false } func main() { node3 := &Node{value: 3, next: nil} node2 := &Node{value: 2, next: node3} node1 := &Node{value: 1, next: node2} found := search(node1, 2) fmt.Printf("List: 1 -> 2 -> 3 -> null\n") fmt.Printf("Search for 2: %v\n", found) }
curr := headfor curr != nil {if curr.value == target {return truecurr = curr.nextreturn falsefor curr != nil {if curr.value == target {return falseval?type Node struct {
value int
next *Node
}
func search(head *Node, val int) bool {
current := head
for current != nil {
if current.value == val {
return true
}
current = current.next
}
return false
}
// List: 1 -> 3 -> 5 -> 7 -> nil
head := &Node{1, &Node{3, &Node{5, &Node{7, nil}}}}
fmt.Println(search(head, 5))func search(head *Node, val int) bool {
current := head
for current.next != nil {
if current.value == val {
return true
}
current = current.next
}
return false
}val instead of just true/false?Pass the test and this pattern moves unknown