/**
* 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) {
//base case: 如果數目不到k, 回傳head
ListNode* next = head;
int i = 0;
while (next && i < k) {
next = next->next;
i++;
}
if (i < k) {
return head;
}
//pre為上一組k group的頭
ListNode* pre = reverseKGroup(next, k);
//reverse當前的k group
ListNode* curr = head;
for (int i = 0; i < k; i++) {
next = curr->next;
curr->next = pre;
pre = curr;
curr = next;
}
return pre;
}
};