← Volver al curso: Lenguaje C desde cero

Lista enlazada dinámica y repaso de la semana 6

Vídeo próximamente

Esta lección junta lo aprendido en la semana: structs, punteros y memoria dinámica. Construirás una lista enlazada, una estructura de datos en la que cada elemento (nodo) se reserva por separado y guarda un puntero al siguiente. A diferencia de un array, crece y decrece nodo a nodo sin copiar datos, y insertar al principio es instantáneo. A cambio, no se puede acceder directamente al elemento i: hay que recorrerla desde el inicio.

El nodo

Un nodo es un struct con un dato y un puntero a otro nodo del mismo tipo. Como el struct se refiere a sí mismo, necesita una etiqueta (struct Node) para poder escribir el puntero dentro de su propia definición. La lista se representa con un puntero al primer nodo, la cabeza; la lista vacía es una cabeza igual a NULL. El último nodo tiene next igual a NULL, lo que marca el final del recorrido.

c
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int value;
    struct Node *next;
} Node;

/* Inserts at the head. Returns the new head, or NULL on failure. */
static Node *push_front(Node *head, int value) {
    Node *node = malloc(sizeof *node);
    if (node == NULL) {
        return NULL;
    }
    node->value = value;
    node->next = head;
    return node;
}

static void print_list(const Node *head) {
    for (const Node *cur = head; cur != NULL; cur = cur->next) {
        printf("%d -> ", cur->value);
    }
    printf("NULL\n");
}

static void free_list(Node *head) {
    while (head != NULL) {
        Node *next = head->next;   /* save before freeing */
        free(head);
        head = next;
    }
}

int main(void) {
    Node *head = NULL;
    for (int i = 1; i <= 4; i++) {
        Node *updated = push_front(head, i * 10);
        if (updated == NULL) {
            free_list(head);
            return 1;
        }
        head = updated;
    }
    print_list(head);          /* 40 -> 30 -> 20 -> 10 -> NULL */
    free_list(head);
    return 0;
}

Observa free_list: guarda el siguiente nodo antes de liberar el actual, porque después de free ya no se puede leer head->next. Es el error más típico al escribir listas. Observa además que push_front devuelve la nueva cabeza: como C pasa por valor, la función no puede modificar la variable head del llamador a menos que recibas un puntero a puntero (Node **head), alternativa que verás en el ejercicio.

Buscar y eliminar

Buscar recorre los nodos hasta hallar el valor. Eliminar exige reconectar la lista: el nodo anterior debe apuntar al siguiente del eliminado, y después se libera el nodo. El caso especial es borrar la cabeza, porque no hay anterior. Usar un puntero a puntero unifica ambos casos: apuntas al enlace que hay que modificar, ya sea la cabeza o el campo next de un nodo.

c
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int value;
    struct Node *next;
} Node;

static Node *find(Node *head, int value) {
    for (Node *cur = head; cur != NULL; cur = cur->next) {
        if (cur->value == value) {
            return cur;
        }
    }
    return NULL;
}

/* Removes the first node holding value. Returns 1 if removed. */
static int remove_value(Node **head, int value) {
    for (Node **link = head; *link != NULL; link = &(*link)->next) {
        if ((*link)->value == value) {
            Node *doomed = *link;
            *link = doomed->next;    /* skip the node */
            free(doomed);
            return 1;
        }
    }
    return 0;
}

int main(void) {
    Node *head = NULL;
    for (int i = 3; i >= 1; i--) {
        Node *n = malloc(sizeof *n);
        if (n == NULL) {
            return 1;
        }
        n->value = i;
        n->next = head;
        head = n;
    }
    printf("found 2: %s\n", find(head, 2) ? "yes" : "no");
    printf("removed 2: %d\n", remove_value(&head, 2));
    printf("found 2: %s\n", find(head, 2) ? "yes" : "no");

    while (head != NULL) {
        Node *next = head->next;
        free(head);
        head = next;
    }
    return 0;
}

Repaso de la semana 6: malloc, calloc, realloc y free gestionan el montón; comprueba siempre NULL, evita fugas, uso tras liberar y doble liberación; un struct agrupa campos de tipos distintos; typedef da nombres cómodos; p->campo accede a través de un puntero; y una lista enlazada combina todo ello. Haz el ejercicio y el quiz.

Pon a prueba lo aprendido

Pregunta 1 de 6

¿Qué devuelve malloc si no hay memoria suficiente?

✎ Mis apuntes

Guardado solo en este navegador. Inicia sesión para tenerlo en tu cuenta.0/5000 caracteres

← AnteriorSiguiente →