So concise code in c++ with O(n) time and O(1) space


  • -1
    H
    ListNode* reverseKGroup(ListNode* head, int k) {
        if (!head || !head->next || k ==1) return head;
        ListNode *p, *q, *r;
        int i = 1;
        q=head;
        p=head->next;
        q->next = NULL;
        while(p && i < k){
            r=p->next;
            p->next=q;
            q=p;
            p=r;
            i++;
        }
        if (i < k){
            return reverseKGroup(q, i);
        }else{
            head->next = reverseKGroup(p, k);
        }
        return q;
    }

Log in to reply
 

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