Figure 8. Delete
Middle/Any Node.
Logic:
first find out pointer
of node to be detete by calling search() function as a nd or tmp pointer
then travesre whole
linked list till cursor match with nd pointer.
If nd pointer match
with head then call remove_front function.
If nd pointer match
with last node then call remove_back function.
If above two condition
fails to find out nd pointer position means nd pointer lies in between.
Hence find out cursor
pointer which locate before nd pointer and assign cursor->next to tmp->next
also make temp->next finally NULL .
Then free memory
allocated to tmp node free(tmp) .
Main Function code:
printf("\n Enter
data of node to be delete:");
scanf("%d",&data);
nd=search(head,data);
head=remove_any(head,nd);
display(head);
C function for remove
any node/ middle node in linked list :-
first search node pointer i.e. nd using
search function
node* remove_any(node* head,node* nd)
{
if(nd == head) //
if node is first node then simply call remove front function
{
head
= remove_front(head);
return head;
}
if(nd->next == NULL)
// if node is last node then call remove back function
{
head
= remove_back(head);
return head;
}
// if the node is in the middle then
traverse linked list to find out nd
node* cursor =
head;
while(cursor != NULL)
{
if(cursor->next
= nd)
break;
cursor
= cursor->next;
}
// after finding nd take one dummy
pointer say tmp and change the pointer
if(cursor != NULL)
{
node*
tmp = cursor->next;
cursor->next
= tmp->next;
tmp->next
= NULL;
free(tmp);
}
return head;
}
No comments:
Post a Comment