algorithm to remove element from single linked list
May 28, 2013 3 Comments
In this algorithm we were not given with the head node but instead given with the node that is to be deleted.
Lets look at an example:
-------------------------------------- Node : 1->20 | 2->30 | 3->40 | 4->50 | 5 -------------------------------------- Node Address: 10 | 20 | 30 | 40 | 50
And assume we want to remove 3rd element where you are given only the THIRD node that is to be deleted.
Output should be: 1,2,4,5
Since you do not have access to the head, change the given node_to_be_deleted in this manner:
-------------------------------------- Node : 1->20 | 2->30 | 4->50 | 4->50 | 5 -------------------------------------- Node Address : 10 | 20 | 30 | 40 | 50
Instead of deleting the 3rd node we are moving 4th node into 3rd node and ignoring 4th node.
/** * Remove element from SLL * @param node element to be removed */ public void removeElement(Node node) { node.value = node.next.value; node.next = node.next.next; }
Recent Comments