Force button topic link
The title
Val == val; delete all nodes in the list where node. val == val and return the new head Node.
Example 1:
Input: the head =,2,6,3,4,5,6 [1], val = 6 output: [1, 2, 3, 4, 5] example 2:
Input: head = [], val = 1 Output: [] Example 3
Input: head = [7,7,7], val = 7
Tip:
The number of nodes in the list is in the range [0, 10^4]
1 <= Node.val <= 50
0 <= val <= 50
Train of thought
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
/ * *Copy the code
- We are given the ListNode function, and it has the next property, so we need to use the
- Deleting an element points next of the element node to the next node of the element node to be deleted
- Since they don’t give us a pointer to the previous element, we use the node’s next attribute, which means that the target element node we remove is cur.next, not cur (to remove cur, we need to know the previous node that pointed to it). Deleting cur.next assigns cur.next-next to cur.next
var removeElements = function(head, val) {
const ret = new ListNode(0,head)
let cur = ret
while (cur.next){
if (cur.next.val === val){
cur.next = cur.next.next
continue
}
cur = cur.next
}
return ret.next
};
Copy the code