AdvancedLesson 15 of 18
Data Structures: List & Stack – C
Linked list with pointer to pointer, array-based stack and ownership rules for memory.
In a linked list, each node consists of a value and a pointer to the next node; the end is NULL. Inserting at the front is cheap, and the list grows without copying. Each node is allocated individually with malloc – and must be freed individually.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int wert;
struct Node *next;
} Node;
Node *push_front(Node *kopf, int wert) {
Node *n = malloc(sizeof *n);
if (n == NULL) { perror("malloc"); exit(EXIT_FAILURE); }
n->wert = wert;
n->next = kopf;
return n; // new head
}
void entferne(Node **kopf, int wert) { // pointer to pointer: no special case for the head
while (*kopf != NULL) {
if ((*kopf)->wert == wert) {
Node *weg = *kopf;
*kopf = weg->next;
free(weg);
return;
}
kopf = &(*kopf)->next;
}
}
void ausgeben(const Node *n) {
for (; n != NULL; n = n->next) printf("%d -> ", n->wert);
printf("NULL\n");
}
void freigeben(Node *n) {
while (n != NULL) {
Node *naechster = n->next; // FIRST remember, THEN free
free(n);
n = naechster;
}
}
int main(void) {
Node *liste = NULL;
for (int i = 3; i >= 1; i--) liste = push_front(liste, i);
ausgeben(liste); // 1 -> 2 -> 3 -> NULL
entferne(&liste, 2);
ausgeben(liste); // 1 -> 3 -> NULL
freigeben(liste);
return 0;
}A stack (last in, first out) is easy to build in an array with a counter. You report error cases (full, empty) via the return value:
#include <stdio.h>
#define MAX 8
typedef struct { int daten[MAX]; int top; } Stack;
int push(Stack *s, int x) {
if (s->top == MAX) return -1; // full
s->daten[s->top++] = x;
return 0;
}
int pop(Stack *s, int *out) {
if (s->top == 0) return -1; // empty
*out = s->daten[--s->top];
return 0;
}
int main(void) {
Stack s = {.top = 0};
for (int i = 1; i <= 3; i++) push(&s, i);
int x;
while (pop(&s, &x) == 0) printf("%d ", x); // 3 2 1
printf("\n");
return 0;
}- Define the owner: whoever calls
mallocor takes over the pointer is responsible forfree. Document it in comments ("returns new memory, caller frees it"). - Remember first, then free: after
free(n),n->nextmust not be read anymore. - Symmetric functions: every
xyz_createhas a matchingxyz_destroy.
WarningFor library functions that allocate memory internally and may return
NULL, the caller must check. A push_front that silently returns NULL when memory runs out would lose the entire list.TipAlways test your list implementation with
-fsanitize=address or valgrind: both show you leaks and accesses to freed nodes right away.