Skip to main content

Posts

Showing posts with the label Linked list. Deletion of node in LL

Deletion of a node from linked list given only that node

We have considered how to create and print the list and delete a node from a list. But often interviewers ask you a question, given a node of the list, how do you delete that node? The problem here is we do not know the head of the list. We just the know one node which we must delete. Well, the solution is much simpler than it appears. Suppose 12 is the node which should be deleted. As we can see from the diagram, we are deleting the next node of 99 by the usual method of linking n to next of next of 12. But the requirement was not to delete next node  but the node with 12 itself. So we will retain the data of that node (99) by copying it to previous node. And now the node with 99 is marked for deletion. Which can be easily deleted as follows. We are assuming that n is the node with 12 as value. n -> data = n -> next -> data; //copy the data n -> next = n -> next -> next; //link to next free( n -> next) ; //delete next of n   ...