Example 1 — Print, count, sum, and print backward
One list, four traversals.
#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;
}
}
static void print_rev(const struct Node *p) {
if (!p) return;
print_rev(p->next);
printf("%d ", p->data);
}
int main(void) {
struct Node *head = new_node(1, new_node(2, new_node(3, new_node(4, NULL))));
int count = 0, sum = 0;
print_list(head);
for (struct Node *p = head; p; p = p->next) { count++; sum += p->data; }
printf("length=%d sum=%d\n", count, sum);
printf("reverse: ");
print_rev(head);
printf("\n");
free_list(head);
return 0;
} How It Works
- A temporary pointer
pwalks the list;headstays put. - Count and sum accumulate during one pass.
print_revrecurses to the end first, then prints on the way back.
