Delete Node in a Linked List
You are given only access to a node to delete (not the head). Delete that node from the linked list. The node to delete is guaranteed not to be the tail.
Example 1
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: 5 is removed: copy next value into current, skip next.
Output: [4,1,9]
Explanation: 5 is removed: copy next value into current, skip next.
Example 2
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Output: [4,5,9]
Solution Approach
Copy the value of the next node into the current node, then set current.next to skip the next node. This effectively "deletes" the current node.
- Set node.val = node.next.val
- Set node.next = node.next.next
Java
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
Complexity Analysis:
Time complexity: O(1)
Space complexity: O(1)