/**
* 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类
*/
void answer(ListNode*q,ListNode*p,ListNode*x)
{
if(x==NULL)
{
while(q!=p)
{
ListNode*y=q;
q=q->next;
y->next=p->next;
p->next=y;
}
}
else
{
while(q!=p)
{
ListNode*y=q;
q=q->next;
x->next=q;
y->next=p->next;
p->next=y;
}
}
}
ListNode* reverseKGroup(ListNode* head, int k)
{
int count=0;
ListNode*p=head;
ListNode*q=head;
ListNode*x=NULL;
ListNode *ans=head;
while(p && count<k)
{
if(count==0)
{
q=p;
}
count++;
if(count==k)
{
ListNode* r=q;
if(x==NULL)
{
ans=p;
}
answer(q,p,x);
p=q;
x=q;
count=0;
}
p=p->next;
}
return ans;
}
};