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 in the list
#include <stdio.h> #include <stdlib.h> // Node structure for linked list typedef struct Node { int data; struct Node* next; } Node; // Function to create a new node Node* create_node(int value) { Node* new_node = (Node*)malloc(sizeof(Node)); new_node->data = value; new_node->next = NULL; return new_node; } // Function to search for a value in the linked list int search_value(Node* head, int target) { Node* current = head; // start at head while (current != NULL) { // while not end of list if (current->data == target) { return 1; // found the value } current = current->next; // move to next node } return 0; // value not found } // Function to print the linked list void print_list(Node* head, int highlight) { Node* current = head; while (current != NULL) { if (current->data == highlight) { printf("[%d ↑] -> ", current->data); // highlight found node } else { printf("[%d] -> ", current->data); } current = current->next; } printf("null\n"); } int main() { // Create linked list 1 -> 2 -> 3 -> null Node* head = create_node(1); head->next = create_node(2); head->next->next = create_node(3); int target = 2; int found = search_value(head, target); print_list(head, found ? target : -1); if (found) { printf("Value %d found in the list\n", target); } else { printf("Value %d not found in the list\n", target); } // Free memory Node* current = head; while (current != NULL) { Node* temp = current; current = current->next; free(temp); } return 0; }
Node* current = head; // start at headwhile (current != NULL) { // while not end of listif (current->data == target) {return 1; // found the valuecurrent = current->next; // move to next nodewhile (current != NULL) {while (current != NULL) {if (current->data == target) {