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) {
        if (head == null) {
            return head;
        }
        ListNode pointer = head;
        for (int i = 0; i < k; i++) {
            // 不足k个,直接返回
            if (pointer == null) {
                return head;
            }
            pointer = pointer.next;
        }

        // 反转heade到pointer之间
        ListNode current = head;
        ListNode pre = null;
        while (current != pointer) {
            ListNode next = current.next;
            current.next = pre;
            pre = current;
            current = next;
        }

        // head为反转后的最后一个,下一个节点为反转后的头节点
        head.next = reverseKGroup(pointer, k);
        
        // 返回反转后的头节点
        return pre;
    }
}