Easy and intuitive code using 2 pointers.


  • 0
    N
    
    class Solution {
    public:
        ListNode* partition(ListNode* head, int x) {
            ListNode *temp = head;
            ListNode *less=NULL,*greaterequal=NULL,*tless=NULL,*tgreater=NULL;
            while(temp){
                if(temp->val<x){
                    if(!less){
                        less = temp;
                        tless = temp;
                    }else{
                        tless->next = temp;
                        tless = tless->next;
                    }
                }else{
                    if(!greaterequal){
                        greaterequal = temp;
                        tgreater = temp;
                    }else{
                        tgreater->next = temp;
                        tgreater = tgreater->next;
                    }
                }
                temp = temp->next;
            }
            if(!greaterequal)   return less;
            if(!less)   return greaterequal;
            tgreater->next = NULL;
            tless->next = greaterequal;
            return less;
        }
    };
    
    

Log in to reply
 

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