From e4eebe167257af44b676ed0012c041713c3f7665 Mon Sep 17 00:00:00 2001 From: cheems Date: Sat, 28 Jun 2025 22:14:04 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=200203.=E7=A7=BB=E9=99=A4?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E5=85=83=E7=B4=A0.md=20=E4=B8=ADJS=E6=97=A0?= =?UTF-8?q?=E8=99=9A=E6=8B=9F=E5=A4=B4=E8=8A=82=E7=82=B9=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E7=9A=84=E4=BB=A3=E7=A0=81=E5=92=8C=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...76\350\241\250\345\205\203\347\264\240.md" | 36 +++++++++++++++++-- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git "a/problems/0203.\347\247\273\351\231\244\351\223\276\350\241\250\345\205\203\347\264\240.md" "b/problems/0203.\347\247\273\351\231\244\351\223\276\350\241\250\345\205\203\347\264\240.md" index ffe04a5b07..9beab14641 100755 --- "a/problems/0203.\347\247\273\351\231\244\351\223\276\350\241\250\345\205\203\347\264\240.md" +++ "b/problems/0203.\347\247\273\351\231\244\351\223\276\350\241\250\345\205\203\347\264\240.md" @@ -452,6 +452,8 @@ func removeElements(head *ListNode, val int) *ListNode { ### JavaScript: +使用虚拟头节点: + ```js /** * @param {ListNode} head @@ -459,19 +461,47 @@ func removeElements(head *ListNode, val int) *ListNode { * @return {ListNode} */ var removeElements = function(head, val) { + // 这样可以避免头节点就是目标值的情况需要特殊处理 const ret = new ListNode(0, head); let cur = ret; - while(cur.next) { - if(cur.next.val === val) { - cur.next = cur.next.next; + while (cur.next) { + // 如果下一个节点的值等于目标值 val,跳过该节点 + if (cur.next.val === val) { + cur.next = cur.next.next; continue; } cur = cur.next; } + // 返回虚拟头节点的下一个节点,即真正的链表头 return ret.next; }; ``` +在原链表上删除: + +```js +/** + * @param {ListNode} head + * @param {number} val + * @return {ListNode} + */ +var removeElements = function(head, val) { + // 先处理头部连续为 val 的节点 + while (head && head.val === val) { + head = head.next; + } + let cur = head; + while (cur && cur.next) { + if (cur.next.val === val) { + cur.next = cur.next.next; // 跳过当前节点 + } else { + cur = cur.next; + } + } + return head; +}; +``` + ### TypeScript: 版本一(在原链表上直接删除):