/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* reverseKGroup(ListNode* head, int k) {
// write code here
ListNode *p=head;int length=0;
while(p!=nullptr){
p=p->next;length++;
}
if(k>length)return head;
int t=length/k;ListNode *head1=head;bool tt=false;
p=head;//p始终指向这组头节点
ListNode *head_temp=head,*temp=head,*head2=head,*q=head,*q2=head;
ListNode *last=head;
//temp
for(int i=0;i<t;i++){
p=q;temp=q;
for(int j=0;j<k;j++){
q=q->next;
}//q始终指向下一组第一个结点
for(int j=0;j<k-1;j++){
head2=temp;
temp=p->next;p->next=p->next->next;temp->next=head2;
head2=temp;
}
p->next=q;
if(tt==false){tt=true;head1=head2;last=p;}
else{
last->next=temp;last=p;
}
}
return head1;
}
};