昨日未完成hard今日完成

This commit is contained in:
Cool 2024-08-24 23:21:34 +08:00
parent c64cae520e
commit c6d8c26bfd
1 changed files with 14 additions and 20 deletions

View File

@ -2,8 +2,6 @@ package com.cool.hot100.linkedlist;
import org.junit.Test; import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/** /**
* @Author Cool * @Author Cool
@ -13,41 +11,37 @@ import java.util.List;
**/ **/
public class Num25 { public class Num25 {
/**
* Date 2024/8/23
* DayNumber 2
* Hard 3
*
* @param head
* @param k
* @return
*/
public ListNode reverseKGroup(ListNode head, int k) { public ListNode reverseKGroup(ListNode head, int k) {
ListNode hair=new ListNode(0); ListNode hair=new ListNode(0);
hair.next=head; hair.next=head;
ListNode pre = hair; ListNode pre = hair;
while (head != null) { while (head != null) {
ListNode tail=pre;
for (int i = 0; i < k; i++) { for (int i = 0; i < k; i++) {
head = head.next; tail = tail.next;
if (head == null) { if (tail == null) {
return hair.next; return hair.next;
} }
} }
ListNode next=head.next; ListNode next=tail.next;
ListNode[] reverse = reverse(head,next); ListNode[] reverse = reverse(head,tail);
pre=nodeHead; head=reverse[0];
nodeHead.next = next; tail=reverse[1];
node = next; pre.next=head;
tail.next=next;
head=next;
pre=tail;
} }
return newHead; return hair.next;
} }
private ListNode[] reverse(ListNode head,ListNode next) { private ListNode[] reverse(ListNode head,ListNode next) {
ListNode node = head; ListNode node = head;
ListNode pre = null; ListNode pre = null;
while (node != null) { ListNode nxt=next.next;
while (node != nxt) {
ListNode net = node.next; ListNode net = node.next;
node.next = pre; node.next = pre;
pre = node; pre = node;