Mental Model
We start at the first item and move step-by-step to the next until we reach the end.
Analogy: Like reading a chain of paper clips one by one from the first to the last without skipping any.
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 ↑
head -> [1] -> [2] -> [3] -> null Printed output: 1 2 3
#include <stdio.h> #include <stdlib.h> // Define node structure typedef struct Node { int data; struct Node* next; } Node; // Function to create a new node Node* createNode(int value) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = value; newNode->next = NULL; return newNode; } // Function to print the linked list void printList(Node* head) { Node* current = head; // Start at head while (current != NULL) { // Traverse until end printf("%d ", current->data); // Print current node's data current = current->next; // Move to next node } printf("\n"); } int main() { // Create linked list 1 -> 2 -> 3 -> null Node* head = createNode(1); head->next = createNode(2); head->next->next = createNode(3); // Print the list printList(head); // Free memory Node* temp; while (head != NULL) { temp = head; head = head->next; free(temp); } return 0; }
Node* current = head; // Start at headwhile (current != NULL) { // Traverse until endprintf("%d ", current->data); // Print current node's datacurrent = current->next; // Move to next nodewhile (current != NULL) {while (current != NULL) {