We can insert a new node in a circular link list. We may insert the node in three different location of the node.
In that case, a new node insert at the first position of an existing list. That is, first node or head of the list will be reset after insertion of the node.
Step 1 : Create a new node.
Step 2 : Travel to the last node of the existing node.
Step 3 : Set the next reference of the new node to the first node of the list.
Step 4 : Set the next reference of the last node to the new node of the list.
Step 5 : Reset the first node.
node *insert_first(node *l){
node *l1;
node *temp;
l1=l;
while(l1->next!=l)
{
l1=l1->next;
}
if(l!=NULL){
temp=(node *)malloc(sizeof(node));
printf("Enter a data : ");
scanf("%d",&temp->i);
temp->next=l;
l1->next=temp;
return temp;
}
else
{
return create(l);
}
}
In that case, a new node insert at the last position of an existing list. That is, first node or head of the list will not be reset after insertion of the node.
Step 1 : Create a new node.
Step 2 : Travel to the last node of the existing node.
Step 3 : Set the next reference of the new node to the next reference of the last node of the list.
Step 4 : Set the next reference of the last node to the new node of the list.
void insert_end(node *l){
node *temp;
node *l1;
l1=l;
if(l!=NULL){
temp=(node *)malloc(sizeof(node));
printf("Enter a data : ");
scanf("%d",&temp->i);
while(l1->next!=l)
{
l1=l1->next;
}
l1->next=temp;
temp->next=l;
}
}
Step 1 : Create a new node.
Step 2 : Read the position of the list where we want to insert the new node.
Step 3 : Travel to the node said position-1.
Step 3 : Set the next reference of the new node to the next reference of the current node of the list.
Step 4 : Set the next reference of the current node to the new node of the list.
void insert_pos(node *l,int pos){
node *temp;
int i;
if(l!=NULL){
temp=(node *)malloc(sizeof(node));
printf("Enter a data : ");
scanf("%d",&temp->i);
for(i=1;i<=pos-2;i++)
{
l=l->next;
}
temp->next=l->next;
l->next=temp;
}
}
#include<stdio.h>
#include<conio.h>
struct linklist
{
int i;
struct linklist *next;
};
typedef struct linklist node;
//prototype declaration
node *insert_first(node *);
void insert_end(node *);
void insert_pos1(node *,int);
node *head;
int main()
{
int c,i,pos;
while(1)
{
printf("4. Insert into begining\n");
printf("5. Insert into end position\n");
printf("6. Insert into position 1\n");
printf("15. Exit\n");
printf("Enter Your choice : ");
scanf("%d",&c);
switch(c)
{
case 4:
head=insert_first(head); // insert from beg
break;
case 5:
insert_end(head); // insert from end
break;
case 6:
printf("Enter position : ");
scanf("%d",&pos);
insert_pos1(head,pos);
break;
}
}
}