Traversal and Search
Walk the list.
Walking the list
Traversal means visiting each node in order. You start at the head and follow next pointers until you reach NULL.
Almost every list algorithm builds on this simple walk.
#include <stdio.h>
#include <stdlib.h>
struct Node { int value; struct Node *next; };
struct Node *make(int v){struct Node*n=malloc(sizeof*n);n->value=v;n->next=NULL;return n;}
int main(void) {
struct Node *head = make(10);
head->next = make(20);
for (struct Node *p = head; p != NULL; p = p->next)
printf("%d ", p->value);
printf("\n");
return 0;
}The traversal pattern
The canonical loop uses a moving pointer p: initialize it to head, continue while p is not NULL, and advance with p = p->next.
Never modify head itself while walking, or you lose the start of the list.
#include <stdio.h>
#include <stdlib.h>
struct Node { int value; struct Node *next; };
struct Node *make(int v){struct Node*n=malloc(sizeof*n);n->value=v;n->next=NULL;return n;}
int main(void) {
struct Node *head = make(1);
head->next = make(2);
struct Node *p = head;
while (p) { printf("%d ", p->value); p = p->next; }
printf("\n");
return 0;
}All lessons in this course
- Singly Linked Lists
- Insertion and Deletion
- Traversal and Search
- Doubly Linked Lists