From 7a1d070c257c16bf01aaf4b95bded65393bc3286 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A8=8B=E5=AE=A3=E9=AD=81?= <13963268+cheng-xuankui@user.noreply.gitee.com> Date: Thu, 26 Dec 2024 20:49:16 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A019.=E5=88=A0=E9=99=A4?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=E7=9A=84=E5=80=92=E6=95=B0=E7=AC=ACN?= =?UTF-8?q?=E4=B8=AA=E8=8A=82=E7=82=B9,=E6=B7=BB=E5=8A=A0=E4=BA=86java?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E4=BD=BF=E7=94=A8=E9=80=92=E5=BD=92=E7=9A=84?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E5=88=A0=E9=99=A4=E5=80=92=E6=95=B0=E7=AC=AC?= =?UTF-8?q?N=E4=B8=AA=E8=8A=82=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...0019.删除链表的倒数第N个节点.md | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0019.删除链表的倒数第N个节点.md b/problems/0019.删除链表的倒数第N个节点.md index fafef1f2..16312d0f 100644 --- a/problems/0019.删除链表的倒数第N个节点.md +++ b/problems/0019.删除链表的倒数第N个节点.md @@ -129,6 +129,36 @@ class Solution { } ``` + +```java +class Solution { + public ListNode removeNthFromEnd(ListNode head, int n) { + // 创建一个新的哑节点,指向原链表头 + ListNode s = new ListNode(-1, head); + // 递归调用remove方法,从哑节点开始进行删除操作 + remove(s, n); + // 返回新链表的头(去掉可能的哑节点) + return s.next; + } + + public int remove(ListNode p, int n) { + // 递归结束条件:如果当前节点为空,返回0 + if (p == null) { + return 0; + } + // 递归深入到下一个节点 + int net = remove(p.next, n); + // 如果当前节点是倒数第n个节点,进行删除操作 + if (net == n) { + p.next = p.next.next; + } + // 返回当前节点的总深度 + return net + 1; + } +} +``` + + ### Python: ```python