25 lines, pure recursive way


  • 0
    K

    reverse and reverseKGroup are self-recursive functions.

    void reverse(struct ListNode **head, struct ListNode *end){
        if((*head) == end){
            return;
        }
        struct ListNode* next = end->next, *second = (*head)->next;
        reverse(&second, end);
        (*head)->next->next = (*head);
        (*head)->next = next;
        (*head) = second;
    }
    
    struct ListNode *reverseKGroup(struct ListNode *head, int k) {
        int temp = k - 1;
        struct ListNode *end = head;
        while(temp && end){
            temp--;
            end = end->next;
        }
        if(!end){
            return head;
        }
        end->next = reverseKGroup(end->next, k);
        reverse(&head, end);
        return head;
    }

Log in to reply
 

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