题目
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
int num=0;
ListNode* temp = head;
while(temp!=NULL)
{
num++;
temp = temp->next;
}
if(k>num||k==1)
return head;
ListNode* start;
ListNode* end;
ListNode* pre;
ListNode* res;
pre = res = new ListNode(0);
temp = head;
int pos=0;
while(temp!=NULL)
{
if((pos==0 || pos%k==0))
{
if(num-pos<k)
break;
if(pos!=0){
pre = end;
}
start = temp;
end = temp;
temp=temp->next;
pos++;
}
else
{
ListNode* term = temp;
temp = temp->next;
end->next = term->next;
term->next = start;
pre->next = term;
start=term;
//pre->next = start;
pos++;
}
}
return res->next;
}
};