import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 相隔k个反转一次!
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        ListNode fake_head = new ListNode(-1);
        fake_head.next = head;
        ListNode pre = fake_head;
        ListNode cur = null;
        ListNode tail = head;
            
        while(tail != null){
            int count = 0;
            cur = tail;
            while(count < k && tail != null){
                tail = tail.next;
                count++;
            }
            if(count < k){
                break;
            }
            ListNode next = pre.next;
            pre.next = reverse(cur,tail);
            pre = next;
        }  
        return fake_head.next;
    }
    
    private ListNode reverse(ListNode head,ListNode tail){
        ListNode cur = head,pre = null,next = null;
        while(cur != tail){
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        head.next = tail;
        return pre;
    }
    
    
}