蒙逼解题法:debug一个小时,解出来头也昏了
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
ListNode left = null;
ListNode right = null;
ListNode cur = head;
ListNode count = head;
// ListNode newHead = null;
int len = 0;
//求链表长度
while(count != null){
len++;
count = count.next;
}
if(len == 0) return null;
if(len == 1) return head;
if(k == 1) return head;
//将长链表分割成大小为k的小链表遍历
for(int j=1;j<=len/k;j++){
ListNode temp = left;
left = cur;
//遍历k,找到待分割部分的left和right
for(int i=1;i<=k;i++){
//if(cur == null) return head;
cur = cur.next;
//if(k == 1){right = cur; cur= cur.next; break;}
if(i == k-1) right = cur;
}
//斩断链表
right.next = null;
//反转部分链表
reverse(left);
left.next = cur;
if(j == 1){
head = right;
}else{
temp.next = right;
}
}
return head;
}
//反转截取到的链表
public void reverse(ListNode head){
ListNode pre = null;
ListNode cur2 = head;
while(cur2 != null){
ListNode cur_next = cur2.next;
cur2.next = pre;
pre = cur2;
cur2 = cur_next;
}
}
}