Delete Node in a Linked List
Medium · Linked List · Explanation and code example
Copy the Successor and Bypass It
How it works
The predecessor is unavailable, but the supplied node is guaranteed not to be the tail. Copy the successor value into the supplied node and bypass the successor. The resulting sequence is the same as deleting the supplied value at that position.
Steps
- Copy node.next.val into node.val.
- Set node.next to node.next.next.
- Finish without traversing the list.
Complexity
- Time: O(1).
- Space: O(1).
Things to watch for
- This relies on the non-tail guarantee.
- The physical supplied node remains; its value and next link change.
- Returning a new head is unnecessary.
Python code example
class Solution:
def deleteNode(self, node):
node.val = node.next.val
node.next = node.next.next
C++ code example
class Solution {
public:
void deleteNode(ListNode* node) {
node->val = node->next->val;
node->next = node->next->next;
}
};
Source and license
Explanation by LC Tracker. Code adapted from walkccc / Peng-Yu Chen · MIT license. Node types are supplied by LeetCode where needed.