8. Insert a node After a node In LL:-
Logic:
Main Function code:
printf("\n Enter data for search a node after which data to be added:");
scanf("%d",&data);
prev=search(head,data);
printf("\n Enter data of node to be insert after:");
scanf("%d",&data1);
head= insert_after(head,data1,prev);
display(head);
Figure 4. Insert node after a Node.
- Find out previous pointer which will point on to node after which we have to add a node.
- To search previous pointer you may call search function which will return pointer whenever data will match in link list.
Main Function code:
printf("\n Enter data for search a node after which data to be added:");
scanf("%d",&data);
prev=search(head,data);
printf("\n Enter data of node to be insert after:");
scanf("%d",&data1);
head= insert_after(head,data1,prev);
display(head);
C function for insert after node in Linked List:-
C function for insert after node:-
node* insert_after(node *head, int data1, node* prev)
{
// now first find the prev node, starting from the first node
node *cursor = head;
while(cursor != prev)
cursor = cursor->next;
// If cursor is not NULL then create a new node having data and pointer of cursor->next
if(cursor != NULL)
{
node* new_node = create(data1,cursor->next);
cursor->next = new_node; // Assign cursor-.next pointer to new node
return head;
}
else
{
return NULL;
}
}
No comments:
Post a Comment