思路很简单,就是头插法翻转cnt次链表就可以了
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode*temp=head;
int len=0;
while(temp!=nullptr){
len++;
temp=temp->next;
}
int cnt=len/k;
ListNode*dummy=new ListNode(-1,head);
ListNode*fast=head;
ListNode*slow=dummy;
for(int i=0;i<cnt;i++){
for(int j=1;j<k;j++){
ListNode*temp1=fast->next;
fast->next=temp1->next;
temp1->next=slow->next;
slow->next=temp1;
}
slow=fast;
fast=slow->next;
}
return dummy->next;
}
};
class Solution {
public:
ListNode*myreverse(ListNode*head,ListNode*end){
ListNode*cur=head;
ListNode*pre=nullptr;
while(cur!=end){
ListNode*nxt=cur->next;
cur->next=pre;
pre=cur;
cur=nxt;
}
return pre;
}
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode*cur=head;
for(int i=0;i<k;i++){
if(cur!=nullptr)
cur=cur->next;
else
return head;
}
ListNode*newhead=myreverse(head,cur);
head->next=reverseKGroup(cur,k);
return newhead;
}
};