Welcome to this comprehensive guide on Circular Linked Lists (CLL)! In this lesson, we'll delve deep into the world of CLL, understanding its operations, advantages, and practical applications. Let's embark on this exciting learning journey together!
A Circular Linked List (CLL) is a special type of Linked List where the last node's next pointer points back to the first node, creating a circular structure. This structure allows traversal in both directions (forward and backward) with ease.
struct Node {
int data;
struct Node* next;
}š Note: Here, data represents the data stored in a node, and next is a pointer to the next node in the list.
Let's create a simple CLL with 5 nodes (0-4).
void createCLL(Node** head_ref, int arr[], int size) {
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = arr[0];
temp->next = temp;
Node* last = temp;
for (int i = 1; i < size; i++) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = arr[i];
newNode->next = (i == size - 1) ? temp : newNode;
last->next = newNode;
last = newNode;
}
*head_ref = temp;
}š” Pro Tip: The above function initializes a circular linked list with a given array and its size.
void printCLL(Node* node) {
do {
printf("%d ", node->data);
node = node->next;
} while (node != head);
}š” Pro Tip: This function prints the elements of the CLL by traversing it in a circular manner.
void insert(Node** head_ref, int data) {
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = data;
if (*head_ref == NULL) {
temp->next = temp;
*head_ref = temp;
} else {
Node* last = *head_ref;
while (last->next != *head_ref)
last = last->next;
temp->next = *head_ref;
last->next = temp;
*head_ref = temp;
}
}š” Pro Tip: This function inserts a new node with the given data at the end of the CLL.
void deleteNode(Node** head_ref, int key) {
if (*head_ref == NULL)
return;
Node* temp = *head_ref;
if (temp->data == key) {
*head_ref = temp->next;
free(temp);
return;
}
do {
if (temp->next->data == key) {
Node* toDelete = temp->next;
temp->next = temp->next->next;
free(toDelete);
return;
}
temp = temp->next;
} while (temp != *head_ref);
}š” Pro Tip: This function deletes the first occurrence of a node with the given key in the CLL.
CLLs are useful when we need a linear data structure that can traverse in both directions, such as in implementation of various algorithms, simulations, and game development.
What is the key advantage of using a Circular Linked List over a traditional Linked List?