C
Beginner
1 min read
Linked Lists with Structs
Example
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node *next;
} Node;
Node *push_front(Node *head, int val)
{
Node *n = malloc(sizeof(Node));
if (!n) { perror("malloc"); exit(EXIT_FAILURE); }
n->value = val;
n->next = head;
return n;
}
void print_list(const Node *head)
{
for (const Node *p = head; p; p = p->next)
printf("%d -> ", p->value);
printf("NULL\n");
}
Node *remove_value(Node *head, int val)
{
Node dummy = {0, head};
Node *prev = &dummy;
while (prev->next) {
if (prev->next->value == val) {
Node *del = prev->next;
prev->next = del->next;
free(del);
break;
}
prev = prev->next;
}
return dummy.next;
}
void free_list(Node *head)
{
while (head) {
Node *next = head->next;
free(head);
head = next;
}
}
int main(void)
{
Node *list = NULL;
for (int i = 5; i >= 1; i--)
list = push_front(list, i);
printf("Initial: "); print_list(list);
list = remove_value(list, 3);
printf("Remove 3: "); print_list(list);
free_list(list);
printf("List freed — no memory leaks\n");
return 0;
}