Delete Middle Node
Implement an algorithm to delete a node in the middle (Le., any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node.
Link here to the repo to solve the problem
👉👌 Tips
Picture the list 1 -> 5 -> 9 -> 12. Removing 9 would make it look like 1 -> 5 -> 12. You only have access to the 9 node. Can you make it look like the correct answer?
👊 Solution 1
This problem has surprisingly a fairly easy solution. We want to check if the Node passed is not null (the list is not empty) or that this is the last node. All we really want to do is shorten the list based on the pivot node passed (the deletion node). So we want to temporarily assign a new node to the next one and transfer all the values of the next node to this current node that we want to "delete". Then we want to assign this node.next with the next node which we hold temporarily.
public static boolean deleteMiddleNode(SingleLinkedListNode singleLinkedListNode) {
if (singleLinkedListNode == null || singleLinkedListNode.next == null) return false;
SingleLinkedListNode next = singleLinkedListNode.next;
singleLinkedListNode.data = next.data;
singleLinkedListNode.next = next.next;
return true;
}
Question borrowed from “Cracking the coding interview”