Simple recursion C++ solution


  • 0
    H
    ListNode* reverseKGroup(ListNode* head, int k, int cur, int N) {
        if (k <= 1 || cur + k > N) return head;
        ListNode *t = head;
        for (int i = 0; i < k-1; i++) {
            ListNode *next = t->next;
            t->next = next->next;
            next->next = head;
            head = next;
        }
        t->next = reverseKGroup(t->next, k, cur + k, N);
        return head;
    }
    
    int listNodeCount(ListNode *head) {
        int cnt = 0;
        while (head != NULL) {
            head=head->next;
            cnt++;
        }
        return cnt;
    }
    
    ListNode* reverseKGroup(ListNode* head, int k) {
        if (head == NULL) return NULL;
        if (k <= 1) return head;
        int N = listNodeCount(head);
        return reverseKGroup(head, k, 0, N);
    }

Log in to reply
 

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