Question
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list 1 -> 2 -> 3 -> 4
is and you were given the third node with value 3
, the linked list should become 1 -> 2 -> 4
AF ter calling your function.
Solutionapproach:swap with Next Node [Accepted]
The usual of deleting a node from node
a linked list next
are to modify the pointer of the node before it, t O Point-to- node after it.
Since we don't have access to the node before the one we want to delete, we cannot modify the next
pointer of T Hat node in any. Instead, we have to replace the value of the node we want to delete with the value in the node after it, and then delete t He node after it.
Because we know that the node we want to delete are not the tail of the list, we can guarantee that this approach is POSSIB Le.
public void DeleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
From for notes (Wiz)
237. Single-linked list remove nodes Delete node in a Linked List