import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
// 解题思路:这个题目每K个为一组,无法知道具体有多少组,每组都会执行相同的反转,
// 所以采用递归的思路
// 通过1个指针滑动到第K+1个元素,即为一下个递归的头节点
// 反转后原来的头节点为尾节点
ListNode tailNext = head;
for(int i=0;i<k;i++){
// 说明链表长度小于k
if(tailNext == null){
return head;
}
tailNext = tailNext.next;
}
ListNode pre =null;
ListNode cur = head;
ListNode next = head;
while(cur!=tailNext){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
// 反转后原来的头节点为尾节点
// 它的下一个节点指向后面的结果
head.next = reverseKGroup(tailNext,k);
return pre;
}
}