My recursive solution in c++


  • 0
    S
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode dummy(INT_MIN);
        dummy.next = head;
        ListNode *prev = &dummy;
        ListNode *cur = head;
        
        for (int i = 0; i < k; i++){
            if (cur == nullptr) return head;
            cur = cur->next;
        }
        
        while (head->next != cur){
            ListNode *tmp = head->next;
            head->next = tmp->next;
            tmp->next = prev->next;
            prev->next = tmp;
        }
        head->next = reverseKGroup(head->next, k);
        
        return dummy.next;
    }

Log in to reply
 

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