From f6d0c4fc63143faf5368f6806d9a7e34fdf0cc32 Mon Sep 17 00:00:00 2001 From: whaifree <49432110+whaibetter@users.noreply.github.com> Date: Fri, 9 Aug 2024 23:49:02 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E5=88=A0=E9=99=A4=E9=93=BE?= =?UTF-8?q?=E8=A1=A8=E5=80=92=E6=95=B0=E7=AC=ACN=E4=B8=AA=E8=8A=82?= =?UTF-8?q?=E7=82=B9=E7=9A=84=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根据LeetCode19题的要求,实现了删除链表倒数第N个节点的功能。通过两个指针分别定位到第N个节点和链表头,当第一个指针移动到链表末尾时,第二个指针将跳过需要删除的节点,从而实现删除操作。提供了两个实现版本,分别在类Solution和类So中。 --- .../redo/redo_all_240721/LeetCode19.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/main/java/cn/whaifree/redo/redo_all_240721/LeetCode19.java diff --git a/src/main/java/cn/whaifree/redo/redo_all_240721/LeetCode19.java b/src/main/java/cn/whaifree/redo/redo_all_240721/LeetCode19.java new file mode 100644 index 0000000..d34702a --- /dev/null +++ b/src/main/java/cn/whaifree/redo/redo_all_240721/LeetCode19.java @@ -0,0 +1,56 @@ +package cn.whaifree.redo.redo_all_240721; + +import cn.whaifree.leetCode.model.ListNode; +import org.junit.Test; + +/** + * @version 1.0 + * @Author whai文海 + * @Date 2024/8/9 21:20 + * @注释 + */ +public class LeetCode19 { + @Test + public void test() { + +// new Solution().removeNthFromEnd(ListNode.listNodeFromArray(new int[]{1, 2, 3, 4, 5}), 2).printList(); + new So().ListNoderemoveNthEromEnd(ListNode.listNodeFromArray(new int[]{1}), 1).printList(); + } + + + class Solution { + public ListNode removeNthFromEnd(ListNode head, int n) { + + ListNode pre = new ListNode(-1, head); + ListNode fast = pre; + ListNode slow = pre; + for (int i = 0; i < n; i++) { + fast = fast.next; + } + + while (fast.next != null) { + fast = fast.next; + slow = slow.next; + } + slow.next = slow.next.next; + return pre.next; + } + } + + class So { + public ListNode ListNoderemoveNthEromEnd(ListNode head, int n) { + ListNode first = new ListNode(0, head); + ListNode second = head; + for (int i = 0; i < n; i++) { + second = second.next; + } + while (second != null) { + first = first.next; + second = second.next; + } + first.next = first.next.next; + return head; + + } + } +}