给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。
k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null || head.next == null) return head;
        ListNode dummy = new ListNode();
        dummy.next = head;  //设置一个虚拟头节点
        ListNode pre,start,end,next;
        pre = dummy;  //每次pre都是反转的那个链表的头节点之前的那个节点
        start = dummy.next; //要反转的那个链表的头节点
        end = getEnd(pre,k); //找到要反转链表的尾节点
        while(end != null){
            next = end.next;  //next为end的下一个节点,也就是下一次循环的start
            end.next = null;  //断开当前尾节点的连接,方便链表部分反转
            pre.next = reverse(start);  //反转链表
            pre = start;  //start是当前的最后一个节点,也就是下一次反转的头节点之前的那个节点(pre)
            start.next = next; //连接断开的链表
            start = next;  //重置start节点
            end = getEnd(pre,k); //获取下一次反转的尾节点
        }
        return dummy.next;
    }
    public ListNode reverse(ListNode head){
        ListNode pre = null;
        ListNode curr = head;
        while(curr != null){
            ListNode next = curr.next;
            curr.next = pre;
            pre = curr;
            curr = next;
        }
        return pre;
    }
    public ListNode getEnd(ListNode pre,int k){
        while(k != 0){
            pre = pre.next;
            if(pre == null) return null;
            k--;
        }
        return pre;
    }
}


















