Delete Node in a Linked List Delete
Problem Summary
You are given only a reference to a node (not the head) in a singly linked list. The node is not the tail.
You need to delete this node from the list.
What You Cannot Do
-
You cannot traverse from the head to find the previous node.
-
You do not have access to the previous node, so you can't modify its
nextpointer.
What You Can Do (The Trick )
You copy the value of the next node into the current node, and then delete the next node instead.
class Node:
def deleteNode(node: ListNode) -> None:
node.val = node.next.val # Step 1: Copy value from next node
node.next = node.next.next # Step 2: Skip the next node