My recursive C++ solution.

  • 0
    class Solution{
        int K;
        pair<ListNode *, ListNode *> reverse(ListNode *head, int k){
            if(!head) return {nullptr, nullptr};
            if(1 == k) return {head, head};
            auto pr = reverse(head->next, k - 1);
                auto nxt = pr.second->next;
                if(k == K){
                    auto tmp = reverse(nxt, K);
                    nxt = tmp.first? tmp.first: nxt;
                head->next =nxt;
                pr.second->next = head;
                pr.second = head;
            return pr;
        ListNode* reverseKGroup(ListNode *head, int k){
            K = k;
            auto ans = reverse(head, k);
            return ans.first? ans.first: head;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.