/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ void reverse(ListNode *&left_pre,ListNode *&left,ListNode* &right,ListNode*& right_last) { ListNode* p=left,* pre=NULL; while(p!=right_last) { ListNode* t=p->next; p->next=pre; if(p!=right) pre=p; p=t; } left_pre->next=right; left->next=right_last; } ListNode* reverseKGroup(ListNode* head, int k) { // write code here if(k==1||head==NULL||head->next==NULL) return head; ListNode* H=new ListNode(0); H->next=head;//头节点 ListNode* pp=head,*pp_pre=H;//遍历 ListNode* left=head,*left_pre=H,*right,*right_last; bool flag_left=0,flag_right=0; int i; for(i=1;pp;i++) { if(i%k==1) { left_pre=pp_pre; left=pp; flag_left=1; } if(i%k==0) { right=pp; right_last=pp->next; flag_right=1; } if(flag_right&&flag_left) { cout<<i<<" "; reverse(left_pre,left,right,right_last); flag_left=flag_right=0; pp_pre=left; pp=right_last; } else { pp_pre=pp; pp=pp->next; } } return H->next; } };