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
        //边界条件
        if(head == null || k <= 1) return head;
        //定义dummy
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode priv = dummy;
        ListNode end = dummy;

        //开始循环
        while(true){
            //找到每组的end的位置,为后面的分组做铺垫
            for(int i=0; i<k && end != null; i++) end = end.next;
            if(end == null) break;
            //定义每组的起始点和新的一组的起始点
            ListNode start = priv.next;
            ListNode NextGroupStart = end.next;
            //截断end的连接,分组
            end.next = null;

            //基础的反转
            priv.next = reverse(start);
            //和下一组连上
            start.next = NextGroupStart;
            priv = start;
            end = priv;
            
        }
        return dummy.next;
    }
    ListNode reverse(ListNode head){
        if(head == null) return head;
        ListNode priv = null;
        ListNode curr = head;
        while(curr != null){
            ListNode next = curr.next;
            curr.next = priv;
            priv = curr;
            curr = next;
        }
        return priv;
    }
}