Program for Insertion and Deletion in Circular Linked list
A Circular Linked list is a complex data structure. The linked list is circular as the last node of the linked list is pointed to the head making a circular loop. The Insertion of a node can be done at the end of the linked list and any node can be deleted from the circular linked list. I will be writing only the insertion and deletion function instead of the whole program.
Code :
struct node
{
int data;
node *next;
}
void insert(node *head,int data)
{
node *current=head; // Assign head to the current node
node temp;
temp=(node*)malloc(sizeof(node));
temp->data=data; // insert data into temporary node
if(head==NULL) // Linked list is Empty
{
head=temp; // make head as temp and temp->next pointed to head
temp->next=head;
}
else
{
while(current->next!=head) // Iterate till the end of linked list and insert element
{
current=current->next;
}
current->next=temp;
temp->next=head;
}
}
void delete(node *head,int data)
{
node *current=head;
while((current->next!=head) && (current->next->data !=data)) // Iterate till the node whose next
{ node you want to delete
current=current->next;
}
node *temp; // Make temporary node and point to the next of the node
temp=current->next; you are present now and delete it.
current->next=temp->next;
free(temp);
}
Code :
struct node
{
int data;
node *next;
}
void insert(node *head,int data)
{
node *current=head; // Assign head to the current node
node temp;
temp=(node*)malloc(sizeof(node));
temp->data=data; // insert data into temporary node
if(head==NULL) // Linked list is Empty
{
head=temp; // make head as temp and temp->next pointed to head
temp->next=head;
}
else
{
while(current->next!=head) // Iterate till the end of linked list and insert element
{
current=current->next;
}
current->next=temp;
temp->next=head;
}
}
void delete(node *head,int data)
{
node *current=head;
while((current->next!=head) && (current->next->data !=data)) // Iterate till the node whose next
{ node you want to delete
current=current->next;
}
node *temp; // Make temporary node and point to the next of the node
temp=current->next; you are present now and delete it.
current->next=temp->next;
free(temp);
}
Comments
Post a Comment