Circular linked list in C: solved exercise
If you need a circular linked list in C solved exercise, this example covers insertion, traversal, and cleanup without infinite loops.
Problem statement
Implement a circular singly linked list with:
- tail insertion,
- full traversal,
- memory deallocation.
C solution
#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;
}Expected output
5 10 15Common mistakes
- Using
while (cur != NULL)instead ofdo-while. - Forgetting to close the cycle back to
head. - Freeing nodes without respecting circular traversal.
Practical use
Circular lists are useful for round-robin scheduling and rotating buffer workflows.
Recommended next exercise
- Binary tree in C: solved insertion and search exercise
- Doubly linked list in C: solved exercise with insert and traversal
- fread and fwrite in C: solved binary file exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
What is the difference between singly and circular linked lists?
In a circular list, the last node points back to the first. In a standard singly list, it points to NULL.
Where are circular lists useful in real projects?
They are useful for turn rotation, repeated task scheduling, and cyclic processing structures.
How do I avoid infinite loops while traversing?
Keep a start pointer and stop when traversal reaches that pointer again.