Singly linked list in C: solved exercise
If you searched for singly linked list in C solved exercise, this example covers real core operations: insert, search, and delete.
Problem statement
Implement a singly linked list with functions to:
- insert at head,
- search a value,
- delete a node,
- free memory.
C solution
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node *next;
} Node;
Node *insert_head(Node *head, int value) {
Node *n = malloc(sizeof(Node));
if (!n) return head;
n->value = value;
n->next = head;
return n;
}
Node *delete_value(Node *head, int value) {
Node *cur = head, *prev = NULL;
while (cur && cur->value != value) {
prev = cur;
cur = cur->next;
}
if (!cur) return head;
if (!prev) head = cur->next;
else prev->next = cur->next;
free(cur);
return head;
}
int contains(Node *head, int value) {
while (head) {
if (head->value == value) return 1;
head = head->next;
}
return 0;
}
void print_list(Node *head) {
while (head) {
printf("%d ", head->value);
head = head->next;
}
printf("\n");
}
void free_list(Node *head) {
while (head) {
Node *tmp = head;
head = head->next;
free(tmp);
}
}
int main(void) {
Node *list = NULL;
list = insert_head(list, 30);
list = insert_head(list, 20);
list = insert_head(list, 10);
printf("Contains 20: %d\n", contains(list, 20));
list = delete_value(list, 20);
print_list(list);
free_list(list);
return 0;
}Expected output
Contains 20: 1
10 30Common mistakes
- Losing updated
headafter insert/delete. - Not handling deletion of first node.
- Forgetting final cleanup.
Practical use
Singly linked lists still appear in lightweight job queues and incremental event pipelines.
Recommended next exercise
- Queue in C: solved exercise with circular array
- Stack in C: solved exercise with push, pop, and peek
- Binary search in C: solved exercise on sorted arrays
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Is this exercise useful for C exams and technical interviews?
Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.
Where can I keep practicing with more solved C exercises?
In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.
How should I practice this exercise type to improve faster?
Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.