Delete a node from a singly linked list in C: solved exercise

Delete a node from a singly linked list in C: solved exercise

If you are looking for delete a node from a singly linked list in c: solved exercise, here is a practical, compilable example focused on the reusable idea behind the exercise.

Problem statement

Delete the value 30 from the list 10 -> 20 -> 30 -> 40.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <stdio.h>
#include <stdlib.h>

typedef struct Nodo {
    int valor;
    struct Nodo *sig;
} Nodo;

Nodo *nuevo_nodo(int valor) {
    Nodo *n = (Nodo *)malloc(sizeof(Nodo));
    if (!n) {
        return NULL;
    }
    n->valor = valor;
    n->sig = NULL;
    return n;
}

Nodo *eliminar_valor(Nodo *cabeza, int valor) {
    Nodo *actual = cabeza;
    Nodo *previo = NULL;

    while (actual && actual->valor != valor) {
        previo = actual;
        actual = actual->sig;
    }
    if (!actual) {
        return cabeza;
    }

    if (!previo) {
        cabeza = actual->sig;
    } else {
        previo->sig = actual->sig;
    }
    free(actual);
    return cabeza;
}

void imprimir(Nodo *cabeza) {
    for (Nodo *p = cabeza; p; p = p->sig) {
        printf("%d", p->valor);
        if (p->sig) {
            printf(" ");
        }
    }
    printf("\n");
}

void liberar(Nodo *cabeza) {
    while (cabeza) {
        Nodo *tmp = cabeza;
        cabeza = cabeza->sig;
        free(tmp);
    }
}

int main(void) {
    Nodo *cabeza = nuevo_nodo(10);
    cabeza->sig = nuevo_nodo(20);
    cabeza->sig->sig = nuevo_nodo(30);
    cabeza->sig->sig->sig = nuevo_nodo(40);
    cabeza = eliminar_valor(cabeza, 30);
    imprimir(cabeza);
    liberar(cabeza);
    return 0;
}

Expected output

1
10 20 40

Common mistakes

  • Not testing edge cases such as small or empty inputs.
  • Not validating indices, pointers, or limits carefully enough.
  • Copying the mechanics without understanding the general pattern.

Practical use

This kind of exercise trains correct reference handling and edge cases in linked or hierarchical structures.

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

Is this exercise useful in practice?

Yes. It is designed to teach a reusable C pattern rather than a one-off toy example.

How should I practice it better?

Change the input data, add edge cases, and rewrite it from scratch without looking at the solution.

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.