题目链接
https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
/**
* 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) {
ListNode res = new ListNode();
ListNode[] k_list = new ListNode[k];
ListNode p = head;
ListNode pre = new ListNode();
ListNode pre_2 = new ListNode();
if(head == null ){return null;}
if(!checkKlistnode(head,k)){return head;}
pre = head;
for(int i=0;i<k;i++){
k_list[i] = p;
if(p!= null){p = p.next;}
}
res = reverseKlistnode(k_list,k);
while(checkKlistnode(p,k)){
pre_2 = p;
for(int i=0;i<k;i++){
k_list[i] = p;
if(p!= null){p = p.next;}
}
pre.next = reverseKlistnode(k_list,k);
pre = pre_2;
}
pre.next = p;
return res;
}
public ListNode reverseKlistnode(ListNode[] k_list,int k){
for(int i=k-1;i>0;i--){
k_list[i].next = k_list[i-1];
}
k_list[0].next = null;
return k_list[k-1];
}
public boolean checkKlistnode(ListNode p,int k){
if(p==null){return false;}
for(int i=k;i>0;i--){
if(p != null){
p=p.next;
}
else{return false;}
}
return true;
}
}