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) {
if(head == null) {
return head ;
}
ListNode cur = head ;
//先找到第一段 (找到第一段的尾结点)
int i = 1;
while(i <= k-1 && cur != null) {
cur = cur.next ;
i ++ ;
}
if(cur == null) {//长度不够,直接返回 当前链表
return head ;
}
//cur此时指向第一段 尾结点
//长度够,处理
ListNode nextHead = cur.next ;//记录第一段之后的链表的 头结点
cur.next = null ;//将第一段分离出来
ListNode res = reverse(head) ;//把第一段反转
//将第一段之后的链表 按组反转
//拼接
head.next = reverseKGroup(nextHead,k) ;
return res ;
}
//反转链表 并返回反转之后的头结点
public ListNode reverse(ListNode head) {
if(head == null) {
return head ;
}
ListNode pre = null ;
ListNode cur = head ;
ListNode next = null ;
while(cur != null) {
next = cur.next ;
cur.next = pre ;
pre = cur ;
cur = next ;
}
return pre ;
}
}