Example 1 — Allocate nodes and follow links
Read through a chain of next pointers, then free the nodes.
#include <stdio.h>
#include <stdlib.h>
struct Node { int data; struct Node *next; };
static struct Node *new_node(int v) {
struct Node *n = malloc(sizeof *n);
if (!n) exit(1);
n->data = v;
n->next = NULL;
return n;
}
int main(void) {
struct Node *a = new_node(1);
a->next = new_node(2);
a->next->next = new_node(3);
printf("third value: %d\n", a->next->next->data);
printf("last next is NULL: %d\n", a->next->next->next == NULL);
free(a->next->next);
free(a->next);
free(a);
return 0;
} How It Works
new_nodeallocates and initializes both fields.- Chaining
->follows links one at a time. - Each node is freed once, last-to-first here because the chain is short.
