/**
 * struct ListNode {
 *    int val;
 *    struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    ListNode* reverseKGroup(ListNode* head, int k) {
        if (!head) return head;
        ListNode* cur = nullptr;
        ListNode* tail = nullptr;
        int i;
        for (i = 0; i < k && head; ++i){
            auto tmp = head;
            head = head->next;
            tmp->next = cur;
            cur = tmp;
            if (!tail) tail = cur;
        }
        if (i < k) {
            return reverseKGroup(cur, i);
        }
        if (tail) tail->next = reverseKGroup(head, k);
        return cur;
    }
};