==思路就是==
一部分一部分翻转,返回头尾指针 最后再一部分一部分拼接起来
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ pair<ListNode*, ListNode*> reverselist(ListNode* first, ListNode* second) { ListNode* res_1=first; ListNode* res_2 = second; ListNode* left = nullptr; while(first!=second) { cout<<first->val<<" "; ListNode* tmp = first->next; first->next = left; left=first; first=tmp; } cout<<second->val<<" "; second->next=left; cout<<endl; return {res_2,res_1}; } ListNode* reverseKGroup(ListNode* head, int k) { // write code here // 先找到要翻转的区间 ListNode* first = head; ListNode* second=head; ListNode* last = head; bool flag = true; vector<pair<ListNode*, ListNode*>> ve; while(last) { for(int i=0;i<k-1;i++) { if(!second) { break; } else { second=second->next; } } if(!second) { last=nullptr; ve.push_back({first,nullptr}); } else { last=second->next; if(flag) { head=second; flag =false; } // cout<<"first: "<<first->val<<" second: "<<second->val<<endl; auto val = reverselist(first, second); ve.push_back(val); first=last; second=last; } } // 开始进行拼接 for(int i=1;i<ve.size();i++) { ve[i-1].second->next=ve[i].first; } return head; } };