A circular linked list in C is a type of linked list where the last node points back to the first node, forming a circular structure. This data structure is useful in applications where traversal needs to be continuous or repeated in a loop.
In this tutorial, we will implement a circular linked list in C and perform the following operations:
- Insert a node at the end of the linked list
- Insert a node before a specified position
- Delete the first node of the linked list
- Delete a node after a specified position
These operations help strengthen understanding of pointer manipulation and circular list behavior in C programming.
C Program for Circular Linked List in C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* head = NULL;
void insertEnd(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
if (head == NULL) {
head = newNode;
newNode->next = head;
return;
}
struct Node* temp = head;
while (temp->next != head)
temp = temp->next;
temp->next = newNode;
newNode->next = head;
}
void insertBeforePosition(int value, int pos) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
if (pos == 1) {
struct Node* temp = head;
while (temp->next != head)
temp = temp->next;
newNode->next = head;
temp->next = newNode;
head = newNode;
return;
}
struct Node* temp = head;
int i = 1;
while (i < pos - 1 && temp->next != head) {
temp = temp->next;
i++;
}
if (i != pos - 1) {
printf("Invalid position\n");
return;
}
newNode->next = temp->next;
temp->next = newNode;
}
void deleteFirst() {
if (head == NULL) return;
struct Node* temp = head;
if (head->next == head) {
free(head);
head = NULL;
return;
}
struct Node* last = head;
while (last->next != head)
last = last->next;
head = head->next;
last->next = head;
free(temp);
}
void deleteAfterPosition(int pos) {
if (head == NULL) return;
struct Node* temp = head;
int i = 1;
while (i < pos && temp->next != head) {
temp = temp->next;
i++;
}
if (temp->next == head) {
printf("No node exists after position %d\n", pos);
return;
}
struct Node* del = temp->next;
temp->next = del->next;
if (del == head)
head = del->next;
free(del);
}
void display() {
if (head == NULL) {
printf("List is empty\n");
return;
}
struct Node* temp = head;
do {
printf("%d -> ", temp->data);
temp = temp->next;
} while (temp != head);
printf("HEAD\n");
}
int main() {
insertEnd(10);
insertEnd(20);
insertEnd(30);
display();
insertBeforePosition(5, 1);
display();
deleteFirst();
display();
deleteAfterPosition(2);
display();
return 0;
}
Why Use Circular Linked List in C?
Using a circular linked list in C offers advantages in real-time applications like buffering, task scheduling, and multiplayer games. Since the last node connects back to the first, it helps in continuous looping structures.