sl1673495/leetcode-javascript

移除链表元素-203

sl1673495 opened this issue · 1 comments

删除链表中等于给定值 val 的所有节点。

示例:

输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5

https://leetcode-cn.com/problems/remove-linked-list-elements

思路

此题的主要思路是建立一个傀儡节点,这样在 while 循环中就只需要考虑对下一个节点的处理。

如果下一个节点值和目标值相同,那么就把 cur.next = cur.next.next 这样转移到下下个节点

还有一个细节需要注意的是,如果下一个节点和目标值相同,此时循环中不需要用 cur = cur.next 把引用转移到下一个节点,因为此时自然而然的进入下一轮循环后,就会对 cur.next 也就是更改过后的待处理next 进行判断和处理。

/**
 * @param {ListNode} head
 * @param {number} val
 * @return {ListNode}
 */
let removeElements = function (head, val) {
    let root = new ListNode()
    root.next = head
    let cur = root
    while (cur) {
        let next = cur.next
        if (!next) {
            break
        }
        let nextVal = next.val
        if (nextVal === val) {
            cur.next = cur.next.next
        } else {
            cur = cur.next
        }
    }
    return root.next
};

if (nextVal === val) { cur.next = cur.next.next }
在[1, 1], val = 1的情况会报错,我改成
while (cur.next && cur.next.val === val) { cur.next = cur.next.next }