My recursive C++ code is concise and easy!


  • 1
    P
    void reverseGroup(ListNode *head, ListNode *tail) {
        ListNode *node = head, *tmp, *pre = node;
        if (!node) return;
        node = node->next;
        while (pre != tail) {
            tmp = node->next;
            node->next = pre;
            pre = node;
            node = tmp;
        }
    }
    
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode *runner = head, *tHead = head;
        for (int i = 1;i < k;++i)
            if (runner) runner = runner->next; else break;
        if (!runner) return head;
        tHead = runner->next;
        reverseGroup(head,runner);
        head->next = reverseKGroup(tHead,k);
        return runner;
    }

  • 0

    The problem says:

    "Only constant memory is allowed."

    You're using O(n/k) memory, due to the recursion.


Log in to reply
 

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