import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
ListNode tail = head;
for(int i = 0; i < k; i++){
//如果剩余长度不足K,则直接返回
if(tail == null){
return head;
}
tail = tail.next;
}
//头插法,pre指向新链表的头节点
ListNode pre = null;
ListNode cur = head;
while(cur != tail){
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
//当前尾指向下一段要反转的链表
head.next = reverseKGroup(cur, k);
return pre;
}
}