My 4ms C solution ,O(n) time ,O(1) space


  • 0
    H
    struct ListNode* reverseKGroup(struct ListNode* head, int k) {
    struct ListNode Head;
    struct ListNode *now = &Head,*last = &Head,*tmp;
    int cnt = 0;
    Head.next = NULL;
    while(head)
        for(cnt = 0,now = last,last = head; cnt < k && head; cnt++)
        {
            tmp = head;
            head = head->next;
            tmp -> next = now -> next;
            now->next = tmp;
        }
    if(k != cnt)
    {
        for(head = now->next,now -> next = NULL;head;)
        {
            tmp = head;
            head = head->next;
            tmp -> next = now -> next;
            now->next = tmp;
        }
    }
    return Head.next;
    }

Log in to reply
 

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