10 lines, 8 ms, C, O(1) Space, O(n) Time


  • -2
    F

    Same as my C++ solution. Just translated it to C, and the time is reduced from 24 ms to 8 ms, C OP!!

    struct ListNode* reverseKGroup(struct ListNode* head, int k) {
        struct ListNode * curr = head, * prev = NULL, * curg = head;
        int i = 0;
        while (curr != NULL){
            struct ListNode * next = curr->next; curr->next = prev; prev = curr; curr = next;
            if (++i < k) continue;
            i = 0;
            curg ->next ?  (curg ->next->next = prev) :  (head = prev); prev = curg; curg = curr;
        }
        for (;i >= 0 && prev != NULL; --i){
            struct ListNode * pprev = prev->next; prev->next = curr; curr = prev; prev = pprev;
        }
        return head;
    }

  • 0
    P

    write everything in one line and you get a one line C++! Great idea! Now try ioccc


  • 0
    F

    Why do you think I never tried ioccc, lol. Naive.


Log in to reply
 

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