Topic:
Write a function that removes a given (non-trailing) node from a linked list. The only argument passed to the function is the node to be deleted.
There is a linked list — head = [4,5,1,9], which can be expressed as:
Example 1: Input: head = [4,5,1,9], node = 5 Output: [4,1,9] Explanation: Given the second node in your list whose value is 5, the strain of the list is 4 -> 1 -> 9 after calling your function.
Example 2: Input: head = [4,5,1,9], node = 1 Output: [4,5,9] Explanation: Given a third node in your list whose value is 1, the strain of the list is 4 -> 5 -> 9 after calling your function. Source: LeetCode
Link: leetcode-cn.com/problems/de…
I’m not going to do LeetCode here.
Traditional delete linked lists
How does traditional list deletion work?
- Modify the pointer to the previous node where the German node is to be deleted
- Moves the pointer of the previous node to the next pointer of the deleted node
Subject train of thought
However, the given parameter in this problem is only the deleted node, so in principle, it is impossible to find the previous node to be deleted through traversal. So, this problem is a little bit arbitrary.
- The value of the next node of the node to be deleted is copied to that node
- The pointer to the node to be deleted points to the next node of the replicated node
In short, copy the next node after the deleted node, and then delete the copied node.
var deleteNode = function(node){
node.val = node.next.val;
node.next = node.next.next;
}
Copy the code