Example 1 — Create a list from an array
A tail pointer makes each append constant time.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
static struct Node *new_node(int value, struct Node *next) {
struct Node *n = malloc(sizeof *n);
if (!n) exit(1);
n->data = value;
n->next = next;
return n;
}
static void print_list(const struct Node *p) {
for (; p; p = p->next) printf("%d%s", p->data, p->next ? " " : "");
printf("\n");
}
static void free_list(struct Node *p) {
while (p) {
struct Node *t = p->next;
free(p);
p = t;
}
}
int main(void) {
int values[] = {5, 10, 15};
struct Node *head = NULL, *tail = NULL;
for (int i = 0; i < 3; i++) {
struct Node *n = new_node(values[i], NULL);
if (!head) head = tail = n;
else { tail->next = n; tail = n; }
}
print_list(head);
free_list(head);
return 0;
} How It Works
- The first node becomes both
headandtail. - Later nodes are linked after
tail, andtailadvances. free_listreleases every node at the end.
