Operations on Circular Linked List (CLL)

beginner
15 min

Operations on Circular Linked List (CLL)

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!

What is a Circular Linked List?

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.

markdown
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.

Creating a Circular Linked List

Let's create a simple CLL with 5 nodes (0-4).

c
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.

CLL Operations

1. Traversing the CLL

c
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.

2. Inserting a Node

c
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.

3. Deleting a Node

c
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.

Practical Usage

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.

Quiz

Quick Quiz
Question 1 of 1

What is the key advantage of using a Circular Linked List over a traditional Linked List?