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
        // 解题思路:
        // 1.找到区间的下一个节点rightNext
        // 2.标记区间的头节点end(反转后的尾节点)
        // 3.循环移动节点rightNext,
        // 当rightNext为null时候,说明区间节点数不够,直接返回原链表
        // 4.while (head != rightNext) 反转列表
        // 5.end.next = reverseKGroup(rightNext,k)
        // 6.返回 pre
        ListNode rightNext = head;
        ListNode end = head;

        for (int i = 1; i <= k; i++) {
            if (rightNext == null) {
                return head;
            }
            rightNext = rightNext.next;
        }

        ListNode pre = null;
        ListNode next = null;

        while (head != rightNext) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }

        end.next =  reverseKGroup ( rightNext,  k);
        return pre;
    }
}