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) {head in C?temp must be a pointer to Node.temp as a pointer and assigns it to head.struct Node {
int data;
struct Node* next;
};
int main() {
struct Node n3 = {30, NULL};
struct Node n2 = {20, &n3};
struct Node n1 = {10, &n2};
struct Node* head = &n1;
struct Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
return 0;
}struct Node {
int data;
struct Node* next;
};
void printList(struct Node* head) {
while (head->next != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}struct Node* temp = head;
while (temp) {
if (temp->data) {
printf("%d -> ", temp->data);
}
temp = temp->next;
}
printf("NULL\n");Pass the test and this pattern moves unknown