Posted on

Description

Submission

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if(head == nullptr) return nullptr;

        ListNode* p = head;
        int t = k;
        for(; p != nullptr && t > 0; t--, p = p->next);
        if(t > 0) return head;
        auto tail = head;

        auto res = reverse(head, k, nullptr);
        tail->next = reverseKGroup(p, k);
        return res;
    }
    
private:
    ListNode* reverse(ListNode* head, int k, ListNode* prev) {
        if(k == 1) {
            head->next = prev;
            return head;
        }
        ListNode* next = head->next;
        head->next = prev;
        return reverse(next, k - 1, head);
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *