From c6d8c26bfded7a8f288ef7a8b1adb60c96167326 Mon Sep 17 00:00:00 2001 From: Cool <747682928@qq.com> Date: Sat, 24 Aug 2024 23:21:34 +0800 Subject: [PATCH] =?UTF-8?q?=E6=98=A8=E6=97=A5=E6=9C=AA=E5=AE=8C=E6=88=90ha?= =?UTF-8?q?rd=E4=BB=8A=E6=97=A5=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/cool/hot100/linkedlist/Num25.java | 34 ++++++++----------- 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/src/main/java/com/cool/hot100/linkedlist/Num25.java b/src/main/java/com/cool/hot100/linkedlist/Num25.java index 78dd779..c62c9e8 100644 --- a/src/main/java/com/cool/hot100/linkedlist/Num25.java +++ b/src/main/java/com/cool/hot100/linkedlist/Num25.java @@ -2,8 +2,6 @@ package com.cool.hot100.linkedlist; import org.junit.Test; -import java.util.ArrayList; -import java.util.List; /** * @Author Cool @@ -13,41 +11,37 @@ import java.util.List; **/ public class Num25 { - /** - * Date 2024/8/23 - * DayNumber 2 - * Hard 3 - * - * @param head - * @param k - * @return - */ public ListNode reverseKGroup(ListNode head, int k) { ListNode hair=new ListNode(0); hair.next=head; ListNode pre = hair; while (head != null) { + ListNode tail=pre; for (int i = 0; i < k; i++) { - head = head.next; - if (head == null) { + tail = tail.next; + if (tail == null) { return hair.next; } } - ListNode next=head.next; - ListNode[] reverse = reverse(head,next); - pre=nodeHead; - nodeHead.next = next; - node = next; + ListNode next=tail.next; + ListNode[] reverse = reverse(head,tail); + head=reverse[0]; + tail=reverse[1]; + pre.next=head; + tail.next=next; + head=next; + pre=tail; } - return newHead; + return hair.next; } private ListNode[] reverse(ListNode head,ListNode next) { ListNode node = head; ListNode pre = null; - while (node != null) { + ListNode nxt=next.next; + while (node != nxt) { ListNode net = node.next; node.next = pre; pre = node;