Mental Model
Look at each item one by one until you 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
class Node: def __init__(self, val): self.val = val self.next = None class LinkedList: def __init__(self): self.head = None def append(self, val): new_node = Node(val) if not self.head: self.head = new_node return curr = self.head while curr.next: curr = curr.next curr.next = new_node def search(self, target): curr = self.head while curr: if curr.val == target: return True curr = curr.next return False # Driver code ll = LinkedList() ll.append(1) ll.append(2) ll.append(3) result = ll.search(2) print(f"Found: {result}")
while curr:if curr.val == target:curr = curr.nextwhile curr:return False
if curr.val == target:head?head.current = head to begin traversal from the first node.class Node:
def __init__(self, data):
self.data = data
self.next = None
def search(head, target):
current = head
while current:
if current.data == target:
return True
current = current.next
return False
# Create linked list: 5 -> 10 -> 15 -> None
head = Node(5)
head.next = Node(10)
head.next.next = Node(15)
print(search(head, 10))
print(search(head, 20))def search(head, target):
current = head
while current.next:
if current.data == target:
return True
current = current.next
return Falsewhile current.next skips checking the last node.while current to check all nodes including last.Pass the test and this pattern moves unknown