Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

移除链表元素-203 #97

Open
sl1673495 opened this issue Jun 25, 2020 · 1 comment
Open

移除链表元素-203 #97

sl1673495 opened this issue Jun 25, 2020 · 1 comment
Labels
待复习 看题解或者做出来很艰难的,需要回顾。 链表

Comments

@sl1673495
Copy link
Owner

sl1673495 commented Jun 25, 2020

删除链表中等于给定值 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
};
@sl1673495 sl1673495 added 待复习 看题解或者做出来很艰难的,需要回顾。 链表 labels Jun 25, 2020
@coder-OD
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
待复习 看题解或者做出来很艰难的,需要回顾。 链表
Projects
None yet
Development

No branches or pull requests

2 participants