This commit is contained in:
Mrhongxing committed 2026-10-13 19:17:51 +08:00
1 parent 55faca1edf
commit 97f3b8d69e
3 files changed
+48 -25

No files matched your search

+35 -25
View File
@@ -1,48 +1,58 @@
package com.hong.www;
public class A25 {
public ListNode reverseList(ListNode root){
ListNode temp=null;
ListNode next=root.next;
while(root!=null){
next=root.next;
root.next=temp;
temp=root;
root=next;
}
return temp;
}
public ListNode reverseKGroup(ListNode head, int k) {
if(k==1||head==null){
return head;
}
ListNode dummy = new ListNode(0, head);
ListNode prev = dummy;
ListNode next;
ListNode curr = head;
int time = 1;
ListNode from =head;
ListNode from1;
int is=0;
while (true) {
while (time < k) {
time++;
for(int i = 0; i < k-1 && curr != null; i++) {
curr = curr.next;
if (curr == null) {
return prev.next;
if(curr==null){
is=1;
break;
}
}
next = curr.next;
curr.next = null;
ListNode temp = prev.next;
ListNode last;
ListNode nexttemp = temp.next;
while (nexttemp != null) {
nexttemp = nexttemp.next;
last = temp;
temp = temp.next;
temp.next = last;
last = temp;
if(is==1){
prev.next=from;
break;
}else if(curr!=null){
next=curr.next;
curr.next=null;
prev.next=reverseList(from);
prev=from;
from=next;
curr=from;
}else{
prev.next=from;
break;
}
prev.next.next = null;
prev.next=temp;
prev=temp;
curr=next;
time=1;
}
//return dummy;
return dummy.next;
}
public static void main(String[] args) {
A25 a25 = new A25();
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
int k = 2;
ListNode result = a25.reverseKGroup(head, k);
while (result != null) {