class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* p=head;
int len=0;
if(head==NULL||head->next==NULL) return head;
while(p)
{
len++;
p=p->next;
}
int m=1,n=k;
while(n<=len)
{
head=reverseBetween(head,m,n);
m=m+k;
n=n+k;
}
return head;
}
ListNode* reverseList(ListNode* head) {
if(head==NULL) return head;
if(head->next==NULL) {return head;}
ListNode* p=head;
ListNode* p1;
ListNode* p2;
p1=p->next;
p2=p->next->next;
p->next=NULL;
while(p2)
{
p1->next=p;
p=p1;
p1=p2;
p2=p2->next;
}
p1->next=p;
return p1;
}
ListNode* reverseBetween(ListNode* head, int m, int n) {
int count=1;
ListNode* p=head,*pre,*plast,*head1,*head2;
if(head==NULL||head->next==NULL) return head;
// ListNode* pre;
while(count<m-1)
{
p=p->next;
count++;
}
pre=p;
head1=p->next;
if(m==1)
head1=head;
while(count<n)
{
p=p->next;
count++;
}
plast=p->next;
p->next=NULL;
head2=reverseList(head1);
if(m==1&&n!=1){ head1->next=plast;return head2;}
else{
pre->next=head2;
head1->next=plast;}
return head;
}
};
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* p=head;
int len=0;
if(head==NULL||head->next==NULL) return head;
while(p)
{
len++;
p=p->next;
}
int m=1,n=k;
while(n<=len)
{
head=reverseBetween(head,m,n);
m=m+k;
n=n+k;
}
return head;
}
ListNode* reverseList(ListNode* head) {
if(head==NULL) return head;
if(head->next==NULL) {return head;}
ListNode* p=head;
ListNode* p1;
ListNode* p2;
p1=p->next;
p2=p->next->next;
p->next=NULL;
while(p2)
{
p1->next=p;
p=p1;
p1=p2;
p2=p2->next;
}
p1->next=p;
return p1;
}
ListNode* reverseBetween(ListNode* head, int m, int n) {
int count=1;
ListNode* p=head,*pre,*plast,*head1,*head2;
if(head==NULL||head->next==NULL) return head;
// ListNode* pre;
while(count<m-1)
{
p=p->next;
count++;
}
pre=p;
head1=p->next;
if(m==1)
head1=head;
while(count<n)
{
p=p->next;
count++;
}
plast=p->next;
p->next=NULL;
head2=reverseList(head1);
if(m==1&&n!=1){ head1->next=plast;return head2;}
else{
pre->next=head2;
head1->next=plast;}
return head;
}
};