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
using System; public class Node { public int Value; public Node Next; public Node(int value) { Value = value; Next = null; } } public class LinkedList { public Node Head; public LinkedList() { Head = null; } public void AddLast(int value) { if (Head == null) { Head = new Node(value); return; } Node curr = Head; while (curr.Next != null) { curr = curr.Next; // advance curr to next node } curr.Next = new Node(value); // add new node at end } public bool Search(int target) { Node curr = Head; while (curr != null) { if (curr.Value == target) return true; // found target value curr = curr.Next; // move to next node } return false; // reached end without finding } public void PrintList() { Node curr = Head; while (curr != null) { Console.Write(curr.Value); if (curr.Next != null) Console.Write(" -> "); curr = curr.Next; } Console.WriteLine(" -> null"); } } public class Program { public static void Main() { LinkedList list = new LinkedList(); list.AddLast(1); list.AddLast(2); list.AddLast(3); list.PrintList(); int searchValue = 2; bool found = list.Search(searchValue); Console.WriteLine(found ? $"Value {searchValue} found in the list" : $"Value {searchValue} not found in the list"); } }
while (curr.Next != null)
{
curr = curr.Next; // advance curr to next node
}if (curr.Value == target)
return true; // found target valuecurr = curr.Next; // move to next nodewhile (curr != null)while (curr != null)if (curr.Value == target)head?=.=, which is correct. Others use invalid operators.class Node {
public int data;
public Node next;
public Node(int d) { data = d; next = null; }
}
Node head = new Node(5);
head.next = new Node(10);
head.next.next = new Node(15);
Node current = head;
bool found = false;
while (current != null) {
if (current.data == 10) {
found = true;
break;
}
current = current.next;
}
Console.WriteLine(found);Node current = head;
while (current.next != null) {
if (current.data == 20) {
Console.WriteLine("Found");
break;
}
current = current.next;
}current.next != null, so it stops before last node.x instead of just checking presence?Pass the test and this pattern moves unknown