Example 1 — A linked stack
Push 1, 2, 3 and pop them all.
#include <stdio.h>
#include <stdlib.h>
struct Node { int data; struct Node *next; };
static void push(struct Node **top, int v) {
struct Node *n = malloc(sizeof *n);
if (!n) exit(1);
n->data = v;
n->next = *top;
*top = n;
}
static int pop(struct Node **top) {
struct Node *n = *top;
int v = n->data;
*top = n->next;
free(n);
return v;
}
int main(void) {
struct Node *top = NULL;
push(&top, 1); push(&top, 2); push(&top, 3);
while (top) printf("pop: %d\n", pop(&top));
printf("empty: %d\n", top == NULL);
return 0;
} How It Works
- Each push adds a node at the head, so the newest item is first.
popfrees the removed node after saving its value.- The loop stops when
topisNULL.
