We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
删除链表中等于给定值 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.next = cur.next.next
还有一个细节需要注意的是,如果下一个节点和目标值相同,此时循环中不需要用 cur = 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 };
The text was updated successfully, but these errors were encountered:
if (nextVal === val) { cur.next = cur.next.next } 在[1, 1], val = 1的情况会报错,我改成 while (cur.next && cur.next.val === val) { cur.next = cur.next.next }
if (nextVal === val) { cur.next = cur.next.next }
while (cur.next && cur.next.val === val) { cur.next = cur.next.next }
Sorry, something went wrong.
No branches or pull requests
删除链表中等于给定值 val 的所有节点。
https://leetcode-cn.com/problems/remove-linked-list-elements
思路
此题的主要思路是建立一个傀儡节点,这样在 while 循环中就只需要考虑对下一个节点的处理。
如果下一个节点值和目标值相同,那么就把
cur.next = cur.next.next
这样转移到下下个节点。还有一个细节需要注意的是,如果下一个节点和目标值相同,此时循环中不需要用
cur = cur.next
把引用转移到下一个节点,因为此时自然而然的进入下一轮循环后,就会对cur.next
也就是更改过后的待处理的next
进行判断和处理。The text was updated successfully, but these errors were encountered: