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 -> [found->2] -> 3 -> null Value 2 found in the list
#include <iostream> using namespace std; struct Node { int data; Node* next; Node(int val) : data(val), next(nullptr) {} }; bool searchValue(Node* head, int target) { Node* curr = head; // start at head while (curr != nullptr) { // traverse until end if (curr->data == target) { return true; // found value } curr = curr->next; // move to next node } return false; // value not found } int main() { // create linked list 1->2->3->null Node* head = new Node(1); head->next = new Node(2); head->next->next = new Node(3); int target = 2; bool found = searchValue(head, target); if (found) { cout << "Value " << target << " found in the list" << endl; } else { cout << "Value " << target << " not found in the list" << endl; } // free memory Node* curr = head; while (curr != nullptr) { Node* next = curr->next; delete curr; curr = next; } return 0; }
Node* curr = head; // start at headwhile (curr != nullptr) { // traverse until endif (curr->data == target) {return true; // found valuecurr = curr->next; // move to next nodereturn false; // value not foundwhile (curr != nullptr) {if (curr->data == target) {return false; // value not found
struct Node {
int data;
Node* next;
};
Node* head = new Node{10, nullptr};
head->next = new Node{20, nullptr};
head->next->next = new Node{30, nullptr};
Node* current = head;
int searchValue = 20;
bool found = false;
while (current != nullptr) {
if (current->data == searchValue) {
found = true;
break;
}
current = current->next;
}
if (found) std::cout << "Value found";
else std::cout << "Value not found";Node* current = head;
int searchValue = 15;
while (current->next != nullptr) {
if (current->data == searchValue) {
std::cout << "Found";
break;
}
current = current->next;
}
if (current == nullptr) std::cout << "Not Found";int searchPosition(Node* head, int value) {
int pos = 1;
Node* current = head;
while (current != nullptr) {
if (current->data == value) return pos;
current = current->next;
pos++;
}
return -1;
}Pass the test and this pattern moves unknown