8 ms C solution


  • 0
    Z
    struct ListNode* reverseKGroup(struct ListNode* head, int k) {
        if(!head || !head->next || k <= 1)
            return head;
        struct ListNode *pre,*cur;
        struct ListNode *res = (struct ListNode*)malloc(sizeof(struct ListNode));
        res->next = head;
        pre = res;
        cur = head;
        while(cur != NULL){
            struct ListNode* pilot = pre->next;
            int i = 0;
            while(pilot != NULL && i < k){
                i++;
                pilot = pilot->next;
            }
            if(i != k)
                break;
            while(cur->next != pilot){
                struct ListNode* nt = cur->next->next;
                cur->next->next = pre->next;
                pre->next = cur->next;
                cur->next = nt;
            }
            pre = cur;
            cur = cur->next;
        }
        return res->next;
       }

Log in to reply
 

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