My solution in C++


  • 0
    ListNode* partition(ListNode* head, int x) {
            if(head==NULL || head->next==NULL) return head;
            
            //1.init
            ListNode* resHead=NULL, *resTail=NULL;
            ListNode* head2=NULL, *tail2=NULL;
            
            //2.traverse [1,4,3,2,5,2] 3
            while(head){
                if(head->val < x){
                    if(resHead==NULL){
                        resHead=resTail=head;
                    }else{
                        resTail=resTail->next=head;    
                    }
                }else{
                    if(head2==NULL){
                        head2=tail2=head;
                    }else{
                        tail2=tail2->next=head;    
                    }
                }
                head=head->next;
            }
            if(tail2) tail2->next=NULL;
            
            //3. ready to return
            if(resHead==NULL){
                resHead=head2;
            }else{
                resTail->next=head2;
            }
            
            return resHead;
        }

Log in to reply
 

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