Singly linked list in C: solved exercise with insert and delete

  2 minutes

If you searched for singly linked list in C solved exercise, this example covers real core operations: insert, search, and delete.

Implement a singly linked list with functions to:

  • insert at head,
  • search a value,
  • delete a node,
  • free memory.
#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;
}
Contains 20: 1
10 30
  • Losing updated head after insert/delete.
  • Not handling deletion of first node.
  • Forgetting final cleanup.

Singly linked lists still appear in lightweight job queues and incremental event pipelines.

If you want a complete path with progressive difficulty:

Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.

In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.