18. Remove nodes from the list
When head.val == val, make the first node of head point to head.next
1. The recursion
var deleteNode = function(head, val) {
if(head.val == val){
return head.next
}
head.next = deleteNode(head.next,val);
return head
}
Copy the code
2. Double pointer
var deleteNode = function(head, val) {
if (head.val == val) return head.next
let pre = head, cur = pre.next
while (cur) {
if (cur.val == val) {
pre.next = cur.next
}
pre = cur
cur = cur.next
}
return head
}
Copy the code
203. Remove linked list elements
1. The iteration
var removeElements = function(head, val) {
const dummyHead = new ListNode(0);
dummyHead.next = head;
let temp = dummyHead;
while(temp.next ! = =null) {
if (temp.next.val == val) {
temp.next = temp.next.next;
} else{ temp = temp.next; }}return dummyHead.next;
}
Copy the code
2. Recursively
var removeElements = function(head, val) {
if (head === null) {
return head;
}
head.next = removeElements(head.next, val);
return head.val === val ? head.next : head;
}
Copy the code