个人思路总结:
和24题一样,依旧采用递归三部曲的形式。
代码如下:
/**
* 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* tmp = head;
for(int i=0;i<k;i++)
{
if(tmp==nullptr)
return head;
tmp = tmp->next;
}
ListNode* last = reverseKGroup(tmp,k);
ListNode* cur = head;
ListNode* next = nullptr;
for(int i=0;i<k;i++)
{
next = cur->next;
cur->next = last;
last = cur;
cur = next;
}
return last;
}
};