Simple 8ms recursive C solution


  • 0
    H
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* getLength(struct ListNode* head) {
        int length = 0;
        
        while(head != NULL) {
            length++;
            head = head->next;
        }
        
        return length;
    }
    
    struct ListNode* reverseList(struct ListNode* head, struct ListNode** tail) {
        struct ListNode* prev = NULL;
        struct ListNode* curr = head;
        struct ListNode* next = NULL;
        
        while(curr != NULL) {
            next = curr->next;
            curr->next = prev;
            if(prev == NULL) {
                *tail = curr;
            }
            prev = curr;
            curr = next;
        }
        
        return prev;
    }
     
    struct ListNode* reverseKGroup(struct ListNode* head, int k) {
        struct ListNode* curr = head;
    
        int length = getLength(head);
        if(length <= 1 || length < k) {
            return head;
        }
        
        int reverseIndex = 0;
        while(reverseIndex++ < (k - 1)) {
            curr = curr->next;
        }
        struct ListNode* remainList = curr->next;
        curr->next = NULL;
        
        struct ListNode* tail = NULL;
        head = reverseList(head, &tail);
        
        tail->next = reverseKGroup(remainList, k);
        
        return head;
    }

Log in to reply
 

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