Files
java/src/com/hong/www/A25.java
T
2026-10-13 19:17:51 +08:00

64 lines
1.6 KiB
Java

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;
ListNode from =head;
ListNode from1;
int is=0;
while (true) {
for(int i = 0; i < k-1 && curr != null; i++) {
curr = curr.next;
if(curr==null){
is=1;
break;
}
}
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;
}
}
return dummy.next;
}
public static void main(String[] args) {
A25 a25 = new A25();
ListNode head = new ListNode(1);
head.next = new ListNode(2);
int k = 2;
ListNode result = a25.reverseKGroup(head, k);
while (result != null) {
System.out.print(result.val + " ");
result = result.next;
}
}
}