How to Create Circular Linked List in C: Syntax and Example
To create a
circular linked list in C, define a node structure with a pointer to the next node and link the last node back to the first node. This forms a loop where traversal continues indefinitely unless stopped explicitly.Syntax
A circular linked list node is defined with a data field and a pointer to the next node. The key is to make the last node's next pointer point back to the head node, creating a circle.
- struct Node: Defines the node structure.
- data: Stores the node's value.
- next: Pointer to the next node.
- last->next = head: Links last node to head to form the circle.
c
struct Node {
int data;
struct Node* next;
};
// To create a circular linked list:
// 1. Create nodes
// 2. Link nodes in sequence
// 3. Set last node's next pointer to head node
// Example:
// head->next = second;
// second->next = third;
// third->next = head; // circular linkExample
This example creates a circular linked list with three nodes and prints their values by traversing the list once.
c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
int main() {
struct Node* head = malloc(sizeof(struct Node));
struct Node* second = malloc(sizeof(struct Node));
struct Node* third = malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = head; // circular link
struct Node* temp = head;
int count = 0;
// Traverse and print 3 nodes to avoid infinite loop
while (count < 3) {
printf("%d ", temp->data);
temp = temp->next;
count++;
}
printf("\n");
free(head);
free(second);
free(third);
return 0;
}Output
1 2 3
Common Pitfalls
Common mistakes when creating circular linked lists include:
- Not linking the last node back to the head, which breaks the circular structure.
- Traversing the list without a stopping condition, causing infinite loops.
- Forgetting to free allocated memory, causing memory leaks.
Always ensure the last node points to the head and use a counter or condition to stop traversal.
c
/* Wrong: last node points to NULL, not circular */ third->next = NULL; /* Right: last node points to head to form circle */ third->next = head;
Quick Reference
- Define node with
struct Nodecontaining data and next pointer. - Link nodes sequentially.
- Make last node's
nextpoint to head to form circle. - Use a counter or condition to avoid infinite traversal.
- Free all allocated nodes after use.
Key Takeaways
A circular linked list links the last node back to the first node to form a loop.
Always set the last node's next pointer to the head node to maintain circularity.
Use a stopping condition when traversing to avoid infinite loops.
Remember to free all allocated memory to prevent leaks.
Careful linking and traversal logic are essential for correct circular linked list behavior.