Insert into a sorted linked list in C: solved exercise

Insert into a sorted linked list in C: solved exercise

If you are looking for insert into a sorted linked list in c: solved exercise, here is a practical, compilable example focused on the reusable idea behind the exercise.

Problem statement

Insert the value 30 into the sorted list 10 -> 20 -> 40 while keeping it ordered.

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
#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 *insertar_ordenado(Nodo *cabeza, int valor) {
    Nodo *n = nuevo_nodo(valor);
    if (!n) {
        return cabeza;
    }
    if (cabeza == NULL || valor < cabeza->valor) {
        n->sig = cabeza;
        return n;
    }

    Nodo *actual = cabeza;
    while (actual->sig && actual->sig->valor < valor) {
        actual = actual->sig;
    }
    n->sig = actual->sig;
    actual->sig = n;
    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(40);
    cabeza = insertar_ordenado(cabeza, 30);
    imprimir(cabeza);
    liberar(cabeza);
    return 0;
}

Expected output

1
10 20 30 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.