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(k == 1 || head == null || head.next == null){
return head;
}
// write code here
ListNode newList = new ListNode(0);
//head开始时指向一组内容的第一个
newList.next = head;
ListNode pre = newList;
ListNode groupEnd = toNextEnd(head, k);
while(head != null && groupEnd != head){
//方案①先移动pre,再移动head
// ListNode tmp = pre.next;
// pre.next = head.next;
// head.next = head.next.next;
// pre.next.next = tmp;
//方案②先移动head,再移动pre
ListNode tmp = head.next;
head.next = tmp.next;
tmp.next = pre.next;
pre.next = tmp;
if(head.next == groupEnd){
pre = head;
head = groupEnd;
groupEnd = toNextEnd(groupEnd, k);
}
}
return newList.next;
}
//返回1、原链,不够一组;2、null或者下一组的第一个节点,说明够一组
public ListNode toNextEnd(ListNode head, int k){
ListNode tmp = head;
for(int i = 0; i< k; i++){
if(head == null){
return tmp;
}
head = head.next;
}
return head;
}
}
