8ms C solution.


  • 0
    P
    struct ListNode* reverseKGroup(struct ListNode* head, int k) {
        if (k == 1) return head;
        
        size_t len, groups, n;
        struct ListNode **p, *groupHead, *node;
        
        // get list length
        for (len = 0, node = head; node; node = node->next)
            len++;
        // group num
        groups = (int)(len / k);
        if (groups == 0)
            return head;
        p = &head;
        while (groups--) {
            if (*p) {
                groupHead = *p;
                node = groupHead->next;
            }
            n = k - 1;  // n node to be reversed in a group
            while (n--) {
                groupHead->next = node->next;
                node->next = *p;
                *p = node;
                node = groupHead->next;
            }
            p = &groupHead->next;
        }
        return head;
    }

Log in to reply
 

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