分段头插法进行每k组的翻转,先把剩余的那部分不用翻转的子链表摘出来,然后再将需要翻转的部分分段翻转,最后将摘出来的部分链表连接到已经翻转好的子链表中。

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) {
        if (head == null || k == 1){
            return head;
        }

        ListNode p = head;
        int num = 0;

        while (p != null){
            p = p.next;
            num ++;
        }

        if (num < k){
            return head;
        }
        p = head;

        int reverseNum = (num - num % k);
        reverseNum --;
        while (reverseNum != 0){

            reverseNum --;
            p = p.next;
        }

        ListNode withoutRe = p.next;
        p.next = null;
        ListNode newNode = new ListNode(-1);
        ListNode curHead = newNode;
        p = head;
        int count = 0;

        while (p != null){

            if (count > 0 && count % k == 0){
                int c = k;
                while (c != 0){
                    c --;
                    curHead = curHead.next;
                }
            }

            ListNode temp = p;
            p = p.next;
            temp.next = curHead.next;
            curHead.next = temp;
            count ++;
        }
        p = newNode;
        while (p.next != null){
            p = p.next;
        }
        p.next = withoutRe;

        return newNode.next;
    }
}