Circular linked list in C: solved insert and traversal exercise

  2 minutes

If you need a circular linked list in C solved exercise, this example covers insertion, traversal, and cleanup without infinite loops.

Implement a circular singly linked list with:

  • tail insertion,
  • full traversal,
  • memory deallocation.
#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
  • Using while (cur != NULL) instead of do-while.
  • Forgetting to close the cycle back to head.
  • Freeing nodes without respecting circular traversal.

Circular lists are useful for round-robin scheduling and rotating buffer workflows.

If you want a complete path with progressive difficulty:

In a circular list, the last node points back to the first. In a standard singly list, it points to NULL.

They are useful for turn rotation, repeated task scheduling, and cyclic processing structures.

Keep a start pointer and stop when traversal reaches that pointer again.