Example 1 — Compare traversal of a list
Walk the chain and count nodes.
#include <stdio.h>
struct Node { int data; struct Node *next; };
int main(void) {
struct Node c = {3, NULL}, b = {2, &c}, a = {1, &b};
struct Node *head = &a;
int count = 0;
for (struct Node *p = head; p; p = p->next) count++;
printf("nodes: %d\n", count);
printf("second value: %d\n", head->next->data);
return 0;
} How It Works
headpoints to nodea.- The loop follows
nextpointers until it reachesNULL. head->next->datajumps one link to read the second value.
