Lista circular en C: ejercicio resuelto con inserción y recorrido

  2 minutos

Si buscas lista circular en C ejercicio resuelto, este ejemplo te enseña cómo insertar nodos y recorrer la lista sin bucles infinitos.

Implementa una lista circular simple con:

  • inserción al final,
  • recorrido completo,
  • liberación de memoria.
#include <stdio.h>
#include <stdlib.h>

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

void insert_end(Node **head, int x) {
    Node *n = malloc(sizeof(Node));
    if (!n) return;
    n->value = x;

    if (*head == NULL) {
        n->next = n;
        *head = n;
        return;
    }

    Node *cur = *head;
    while (cur->next != *head) cur = cur->next;

    cur->next = n;
    n->next = *head;
}

void print_list(Node *head) {
    if (!head) return;
    Node *cur = head;
    do {
        printf("%d ", cur->value);
        cur = cur->next;
    } while (cur != head);
    printf("\n");
}

void free_list(Node **head) {
    if (!*head) return;
    Node *cur = (*head)->next;
    while (cur != *head) {
        Node *tmp = cur;
        cur = cur->next;
        free(tmp);
    }
    free(*head);
    *head = NULL;
}

int main(void) {
    Node *head = NULL;
    insert_end(&head, 5);
    insert_end(&head, 10);
    insert_end(&head, 15);

    print_list(head);
    free_list(&head);
    return 0;
}
5 10 15
  • Recorrer con while (cur != NULL) en lugar de do-while.
  • No cerrar el ciclo apuntando al head.
  • Liberar memoria sin romper el recorrido circular.

Las listas circulares se usan en planificación round-robin y buffers con rotación.

Si quieres una ruta completa con progresión real de dificultad:

En la circular, el último nodo apunta al primero. En la simple, el último termina en NULL.

Para repartir turnos, tareas repetitivas y estructuras cíclicas de procesamiento.

Usa un puntero inicial de referencia y detén el recorrido cuando vuelvas a ese nodo.