/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ struct ListNode* reverseKGroup(struct ListNode* head, int k ) { // write code here struct ListNode* tail,*phead,*phead1,*phead2,*befor=NULL,*befor1=NULL; int i; tail=phead=befor=head; if(head==NULL)return NULL; if((k<=1)||(head->next==NULL))return head; //第一次反转 for( i=1;i<k;i++){ if(tail->next!=NULL){ tail=tail->next; }else break; } if(!(i==k)){return head;} head=tail; if((phead->next->next==NULL)||(k==2)){ phead->next=tail->next; tail->next=phead; }else { phead1=phead->next; phead->next=tail->next; phead2=phead1->next; while(phead!=tail){ phead1->next=phead; phead=phead1; phead1=phead2; if(phead2!=tail){ phead2=phead2->next; } } } if(befor->next!=NULL){//后续反转 while(1){ if(befor->next!=NULL){//初始化phead和tail phead=tail=befor->next; befor1=befor->next; }else break; for(i=1;i<k;i++){//找尾 if(tail->next!=NULL){ tail=tail->next; }else break; } if(!(i==k)){break;} befor->next=tail; befor=befor1; if(k==2){ phead->next=tail->next; tail->next=phead; }else{ phead1=phead->next; phead2=phead1->next; phead->next=tail->next; while(phead!=tail){ phead1->next=phead; phead=phead1; phead1=phead2; if(phead2!=tail){ phead2=phead2->next; } } } } } return head; }