class Solution {
public:
ListNode* cal(ListNode* head,int K){
ListNode *now=head->next,*nex=now->next,*nexnex;int cnt=0,flag=0;
while(nex&&++cnt<K) nexnex=nex->next,nex->next=now,now=nex,nex=nexnex,flag|=(cnt==K-1);
ListNode *ans;
if(!flag&&K!=1){//说明不足K个
ans=now,nex=now->next;
while(now!=head->next) nexnex=nex->next,nex->next=now,now=nex,nex=nexnex;
ans->next=NULL;
}else{
ans=head->next;
ans->next=nex,head->next=now;
}
return ans;
}
ListNode* reverseKGroup(ListNode* fir, int K) {
//if(K==1) return fir;
ListNode *head=new ListNode(),*now=head;
head->next=fir;
while(now->next) now=cal(now,K);
return head->next;
}
};
leetcode 25. K 个一组翻转链表
于 2021-02-12 13:09:20 首次发布