24ms c++ solution, O(1) space and O(n) time complexity


  • 0
    A
    class Solution {
    public:
        ListNode* reverseKGroup(ListNode* head, int k) {
            int n=k-1;
            ListNode *temp, *curr, *next, *prev, *start;
            temp=head;
            if(head==NULL)
                return head;
            if(k==1)
                return head;
            while(n>0 && !(temp==NULL || temp->next==NULL)){
                n--;
                temp=temp->next;
            }
            if(n>0)
                return head;
            n=k-1;
            temp=head;
            start=temp;
            prev=temp;
            curr=temp->next;
            next=curr->next;
            while(n>0){
                curr->next=prev;
                prev=curr;
                curr=next;
                if(next!=NULL)
                    next=next->next;
                n--;
            }
            head=prev;
            start->next=reverseKGroup(curr, k);
            return head;
        }
    };

Log in to reply
 

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