Time Complexity: O(1)
Copy the value from the next node: node.val = node.next.val
Update the pointer to skip the next node: node.next = node.next.next
No loops, no recursion, no operations that depend on the size of the linked list. It always takes the same amount of time.
We're not actually deleting the node we were given. Instead, we're:
Overwriting its value with the next node's value
Bypassing the next node by updating the pointer to skip over it
So if we have: 1 -> [2] -> 3 -> 4 (delete node with value 2)
After the operation: 1 -> [3] -> 4
The node object at the second position still exists in memory at the same location, but now it:
Contains the value 3 (copied from the next node)
Points directly to the node with value 4
The original "node 3" is now orphaned (no references to it), so it becomes eligible for garbage collection.
Space Complexity: O(1)
class Solution {
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
}
Top comments (0)