A circular linked list is one in which the nodes are linked in such a way that they form a circle, with the last node pointing to the first node. There are no nodes in a circular linked list that have a null address space.
There are two types:
1) Singly Linked List:
- It establishes a link to the first node by substituting the address of the first node for NULL.
- With the help of circular link generation, the Singly Linked List allows you to access the preceding node.
2) DLL (Doubly Linked List):
- A DLL (Doubly Linked List) has an extra pointer called the prior pointer.
The Benefits of a Singly and Doubly Linked List
- Even if traversing ahead from a specific place, aids in obtaining earlier node information.
- DLL is capable of traversing both forward and backward.
- Due to the prior pointer, DLL is faster in retrieving previous node information.
- Because it does not have a preceding pointer, a singly linked list takes up less space than a doubly linked list.
Algorithm
Addition of node at beginning of Circular linked list
- Step 1. START
- Step 2. Store the data to create a linked list.
- Step 3. Enter the element to be at beginning of the list.
- Step 4. Swap the address (header) of the first node.
- Step 5. The first node address is swapped with the second node repeat till the last node address is swapped with the new first node address.
- Step 6. STOP
Program
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *head = NULL, *x, *y, *z;
void ins_at_beg();
void display();
int main()
{ int c;
x = (struct node*)malloc(sizeof(struct node));
printf("\n Enter the data to create linked list:");
scanf("%d", &x->data);
x->link = x;
head = x;
printf("\n If you wish to continue press 1 otherwise 0:");
scanf("%d", &c);
while (c != 0)
{
y = (struct node*)malloc(sizeof(struct node));
printf("\n Enter the data:");
scanf("%d", &y->data);
x->link = y;
y->link = head;
x = y;
printf("\n If you wish to continue press 1 otherwise 0:");
scanf("%d", &c);
}
ins_at_beg();
display();
}
void ins_at_beg()
{
x = head;
y = (struct node*)malloc(sizeof(struct node));
printf("\n Enter the data to insert at beggining:");
scanf("%d", &y->data);
while (x->link != head)
{
x = x->link;
}
x->link = y;
y->link = head;
head = y;
}
void display()
{
if (head == NULL)
printf("\n List is empty");
else
{
x = head;
while (x->link != head)
{
printf("%d->", x->data);
x = x->link;
}
printf("%d", x->data);
}
}
Output
Enter the data to create a linked list:10
If you wish to continue press 1 otherwise 0:1
Enter the data:15
If you wish to continue press 1 otherwise 0:1
Enter the data:20
If you wish to continue press 1 otherwise 0:1
Enter the data:25
If you wish to continue press 1 otherwise 0:1
Enter the data:30
If you wish to continue press 1 otherwise 0:1
Enter the data:35
If you wish to continue press 1 otherwise 0:0
Enter the data to insert at beggining:5
5->10->15->20->25->30->35