02.03. Delete Middle Node
Description
Implement an algorithm to delete a node in the middle (i.e., any node but the first and last node, not necessarily the exact middle) of a singly linked list, given only access to that node.
Example:
Input: the node c from the linked list a->b->c->d->e->f Output: nothing is returned, but the new linked list looks like a->b->d->e->f
Solutions
Solution 1: Node Assignment
Thinking
Deletion usually needs the predecessor. Only the target node is given, and it is not the tail, so there is no way to walk backward.
The observable effect is that this position’s value and successor link vanish. Copying the next value into the current node and skipping the next node looks like a deletion to the caller.
The two assignments node.val = node.next.val and node.next = node.next.next suffice in constant time and space.
We can replace the value of the current node with the value of the next node, and then delete the next node. This way, we can achieve the purpose of deleting the current node.
The time complexity is \(O(1)\), and the space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |