import java.util.*;

/*
 * 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
        int length = 0;
        ListNode newHead = head;
        while (newHead != null) {
            length++;
            newHead = newHead.next;
        }
        if (length < k || k == 1) {
            return head;
        }
        int n = length / k;
        int start = 1;
        int end = k;
        ListNode node = head;
        while (n != 0) {
            node = reverseBetween(node, start, end);
            start += k;
            end += k;
            n--;
        }
        return node;
    }
    public ListNode reverseBetween(ListNode head, int m, int n) {
        /*
        题解代码
        * */
        /*ListNode newHead = new ListNode(-1);
        newHead.next = head;
        ListNode pre = newHead;
        for (int i = 0; i < m - 1; i++) {
            pre = pre.next;
        }
        ListNode cur = pre.next;
        ListNode next;
        for (int i = 0; i < n - m; i++) {
            next = cur.next;
            cur.next = next.next;
            next.next = pre.next;
            pre.next = next;
        }
        return newHead.next;*/
        /*
         * 自写代码
         * */
        ListNode newHead = new ListNode(-1);
        newHead.next = head;
        ListNode pre = newHead;
        for (int i = 0; i < m - 1; i++, n--) {
            pre = pre.next;
        }
        ListNode cur = pre.next;//找到需要断开的结点
        pre.next = null;
        ListNode rHead = cur;
        for (int i = 0; i < n - 1; i++) {
            rHead = rHead.next;
        }
        ListNode tail = rHead.next;
        rHead.next = null;
        ListNode newPre = null;
        ListNode rTail = cur;
        while (cur != null) {
            ListNode temp = cur.next;
            cur.next = newPre;
            newPre = cur;
            cur = temp;
        }
        pre.next = newPre;
        rTail.next = tail;
        return newHead.next;
    }
}