Appearance
203. 移除链表元素
js
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} val
* @return {ListNode}
*/
var removeElements = function(head, val) {
let cur = head
let prev = null
while(cur !== null) {
// 如果是链头,head后移
if (head.val === val) {
head = head.next
// 如果命中,删除元素
} else if (cur.val === val) {
prev.next = cur.next
// 如果没有命中,全部向后移动
} else {
prev = cur
}
cur = cur.next
}
return head
};