Implement an algorithm to delete a node in the middle of a single linked list, givenonly access to that node
EXAMPLE
Input: the node ‘c’ from the linked list a->b->c->d->e
Result: nothing is returned, but the new linked list looks like a->b->d->e
=================
Analysis:
We can do nothing to delete the target as we do not have the target node's previous node. However, we can copy all the attribute of the node after the target node (say "next node") to target node, then delete the "next node". Result of which is similar to deleting the current node.
Node that if target node is the last node of the linked list, this approach would not work.
public class Answer {
public static void solution(LinkedListNode target){
if(target == null || target.next == null) return;
LinkedListNode next = target.next;
target.data = next.data;
target.next = next.next;
return;
}
public static void main(String[] args) {
LinkedListNode head = AssortedMethods.randomLinkedList(10, 0, 10);
System.out.println(head.printForward());
solution(head.next.next.next); // delete node 4
System.out.println(head.printForward());
}
}
Note: Please download the crackcode library before running the program.