C language, O(n) solution (8ms)


  • 0
    B
     /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* reserveNNodes(struct ListNode* prior, int n)
    {
        struct ListNode* head = prior->next;
        struct ListNode* pointer = head->next;
        struct ListNode* newHead = head;
        
        for(int i = 0; i < n - 1; ++i)
        {
            head->next = pointer->next;
            pointer->next = newHead;
            newHead = pointer;
            prior->next = newHead;
            pointer = head->next;
        }
        
        return head;
    }
    
    struct ListNode* reverseKGroup(struct ListNode* head, int k) {
        if(k <= 1) return head;
        struct ListNode* pointer = (struct ListNode*)malloc(sizeof(struct ListNode*));
        pointer->next = head;
        struct ListNode* head0 = pointer;
        int counter = 0;
        
        while(pointer->next != NULL)
        {
            ++counter;
            pointer = pointer->next;
        }
        if(counter < k) return head;
        
        pointer = head0;
        int loop = counter / k;
        
        for(int i = 0; i < loop; ++i)
        {
            pointer = reserveNNodes(pointer, k);
        }
        
        return head0->next;
    }

Log in to reply
 

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