计数,数量到达k就翻转该组。pre用来存储该组的上一个元素,nextpre用来存储该组的最后一个元素的下一个元素
翻转这块有点绕
/**
* 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) {
ListNode* start=new ListNode(-1);
start->next=head;
ListNode* pre=start;
ListNode* cur0=head;
for(int i=1;cur0!=NULL;i++){
if(i%k==0){
pre=partReverse(pre,cur0->next);
cur0=pre->next;
}
else{
cur0=cur0->next;
}
}
return start->next;
}
ListNode* partReverse(ListNode* pre,ListNode* nextpre){
ListNode* last=pre->next;
ListNode* cur=last->next;
while(cur!=nextpre){
last->next=cur->next;
cur->next=pre->next; //!!!
pre->next=cur;
cur=last->next;
}
return last;
}
};