Circulr Linked List
Circulr Linked List
A circular linked list is a data structure where the last node connects back to the first, forming a
loop. This structure allows for continuous traversal without any interruptions.
Scheduling.
Managing playlists.
It is linked list where all the nodes are connected to form a circle. Unlike a regular linked list, which
ends with a node pointing to NULL, the last node in a circular linked list points back to the first node.
This means that you can keep traversing the list without ever reaching a NULL value.
We can create a circular linked list from both singly linked lists and doubly linked lists. So, circular
linked list are basically of two types:
In Circular Singly Linked List, each node has just one pointer called the “next” pointer. The next
pointer of last node points back to the first node and this results in forming a circle. In this type of
Linked list we can only move through the list in one direction.
In circular doubly linked list, each node has two pointers prev and next, similar to doubly linked list.
The prev pointer points to the previous node and the next points to the next node. Here, in addition
to the last node storing the address of the first node, the first node will also store the address of
the last node.
Create/Declare a Node of Circular Linked List
struct Node
{
int data;
struct Node *next;
};
return newNode;
}
// Initilize nodes
first->data = 2;
second->data = 3;
last->data = 4;
// Connect nodes
first->next = second;
second->next = last;
last->next = first;
Why have we taken a pointer that points to the last node instead of the first node?
For the insertion of a node at the beginning, we need to traverse the whole list. Also, for insertion at
the end, the whole list has to be traversed. If instead of the start pointer, we take a pointer to the
last node, then in both cases there won’t be any need to traverse the whole list. So insertion at the
beginning or at the end takes constant time, irrespective of the length of the list.
Operations on the Circular Linked list:
We can do some operations on the circular linked list similar to the singly and doubly linked list
which are:
Insertion
o Insertion at the empty list
o Insertion at the beginning
o Insertion at the end
o Insertion at the given position
Deletion
o Delete the first node
o Delete the last node
o Delete the node from any position
Searching
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* next;
};
return 0;
}