From 28460715b62e83a89f32db41a9bcafae19f31b5e Mon Sep 17 00:00:00 2001 From: Flow-sandyu <72751523+Flow-sandyu@users.noreply.github.com> Date: Tue, 27 Sep 2022 20:39:27 +0800 Subject: [PATCH 1/2] =?UTF-8?q?Update=200019.=E5=88=A0=E9=99=A4=E9=93=BE?= =?UTF-8?q?=E8=A1=A8=E7=9A=84=E5=80=92=E6=95=B0=E7=AC=ACN=E4=B8=AA?= =?UTF-8?q?=E8=8A=82=E7=82=B9.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改了0019.删除链表的倒数第N个节点 java 版本 --- ...0019.删除链表的倒数第N个节点.md | 43 ++++++++++--------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/problems/0019.删除链表的倒数第N个节点.md b/problems/0019.删除链表的倒数第N个节点.md index 00caeea0..c7f79b8d 100644 --- a/problems/0019.删除链表的倒数第N个节点.md +++ b/problems/0019.删除链表的倒数第N个节点.md @@ -87,30 +87,31 @@ public: java: ```java -class Solution { - public ListNode removeNthFromEnd(ListNode head, int n) { - ListNode dummy = new ListNode(-1); - dummy.next = head; +public ListNode removeNthFromEnd(ListNode head, int n){ + ListNode dummyNode = new ListNode(0); + dummyNode.next = head; - ListNode slow = dummy; - ListNode fast = dummy; - while (n-- > 0) { - fast = fast.next; - } - // 记住 待删除节点slow 的上一节点 - ListNode prev = null; - while (fast != null) { - prev = slow; - slow = slow.next; - fast = fast.next; - } - // 上一节点的next指针绕过 待删除节点slow 直接指向slow的下一节点 - prev.next = slow.next; - // 释放 待删除节点slow 的next指针, 这句删掉也能AC - slow.next = null; + //排除示例 2 的情况:head = [1], n = 1 + if (head == null) + return null; - return dummy.next; + ListNode fastIndex = dummyNode; + ListNode slowIndex = dummyNode; + + //只要快慢指针相差 n 个结点即可 + for (int i = 0; i < n ; i++){ + fastIndex = fastIndex.next; } + + while (fastIndex.next != null){ + fastIndex = fastIndex.next; + slowIndex = slowIndex.next; + } + + //此时 slowIndex 的位置就是待删除元素的前一个位置。 + //具体情况可自己画一个链表长度为 3 的图来模拟代码来理解 + slowIndex.next = slowIndex.next.next; + return dummyNode.next; } ``` From 87c505371df01e7d62e422b796de66d92754fced Mon Sep 17 00:00:00 2001 From: Flow-sandyu <72751523+Flow-sandyu@users.noreply.github.com> Date: Tue, 27 Sep 2022 21:01:31 +0800 Subject: [PATCH 2/2] =?UTF-8?q?Update=200019.=E5=88=A0=E9=99=A4=E9=93=BE?= =?UTF-8?q?=E8=A1=A8=E7=9A=84=E5=80=92=E6=95=B0=E7=AC=ACN=E4=B8=AA?= =?UTF-8?q?=E8=8A=82=E7=82=B9.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0019.删除链表的倒数第N个节点.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/problems/0019.删除链表的倒数第N个节点.md b/problems/0019.删除链表的倒数第N个节点.md index c7f79b8d..a84c0b29 100644 --- a/problems/0019.删除链表的倒数第N个节点.md +++ b/problems/0019.删除链表的倒数第N个节点.md @@ -91,10 +91,6 @@ public ListNode removeNthFromEnd(ListNode head, int n){ ListNode dummyNode = new ListNode(0); dummyNode.next = head; - //排除示例 2 的情况:head = [1], n = 1 - if (head == null) - return null; - ListNode fastIndex = dummyNode; ListNode slowIndex = dummyNode;