Traversing the list with a while loop
What you'll learn: How to use a pointer to visit every node in a linked list until you reach the end.
The "Breadcrumb" Strategy
Think of a linked list like a scavenger hunt. Unlike an array, where all the items are sitting in a row, linked list nodes are scattered across your computer's memory. You can't jump to the middle; you have to start at the beginning (the head) and follow the "breadcrumbs" (the next pointers) one by one.
To do this, we use a temporary "tracker" pointer. We start this tracker at the head, do something with the data there, and then move it to the next node. We keep doing this until the tracker hits a dead end—which, in C, is represented by NULL.
Using a while loop
The most common way to move through a list is a while loop. The logic is simple: "While my tracker is not pointing at nothing, keep moving."
Inside the loop, there is one critical line of code: current = current->next;. This is how you "step" forward. It tells the computer to look at the address stored in the current node's next pointer and jump to that new location.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void printList(struct Node* head) {
// 1. Start a temporary pointer at the head
struct Node* current = head;
// 2. Loop until we hit the end (NULL)
while (current != NULL) {
// 3. Process the data in the current node
printf("%d -> ", current->data);
// 4. Move the pointer to the next node
current = current->next;
}
printf("NULL\n");
}
Why not use the 'head' pointer?
You might wonder why we create a current pointer instead of just moving the head. If you move the head pointer to traverse the list, you lose the starting address of your list forever. It’s like burning the map behind you as you walk. By using a temporary current pointer, your head stays safely at the start, and you can traverse the list as many times as you need.
Key takeaway
To traverse a list, initialize a temporary pointer to the head and use current = current->next inside a while (current != NULL) loop to move from node to node.