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

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        if (head == null || head.next == null || k < 2) {
            return head;
        }
        Deque<ListNode> dq = new LinkedList<>();
        ListNode dummyHead = new ListNode(-1);
        ListNode tail = dummyHead;
        ListNode cur = head;
        int i = k;
        int len = 0;
        while (cur != null) {
            len++;
            dq.offer(cur);
            cur = cur.next;
            i--;
            if (i == 0) {
                while (!dq.isEmpty()) {
                   ListNode node = dq.pollLast();
                   tail.next = node;
                   tail = node;
                }
                i = k;
            }
        } 
        if (len < k) {
            return head;
        }
        while (!dq.isEmpty()) {
            cur = dq.pollFirst();
            tail.next = cur;
            tail = cur;
        }
        tail.next = null;
        
        return dummyHead.next;
    }
}