Simple Java solution with explanation


  • 0
    //The basic idea is that create two LinkedList then combine them together
    public ListNode partition(ListNode head, int x) {
            if(head==null||head.next==null) return head;
            ListNode first=null;
            ListNode firstHead=null;
            ListNode secondHead=null;
            ListNode second=null;
            ListNode cur=head;
            while(cur!=null){
                if(cur.val<x){
                    if(first==null) {first=cur; firstHead=first;}
                    else {first.next=cur; first=first.next;}
                }
                else{
                    if(second==null) {second=cur; secondHead=second;}
                    else {second.next=cur; second=second.next;}
                }
                cur=cur.next;
            }
            
            if(first==null) {
                second.next=null;
                return secondHead;
            }
            else if(second==null){
                return firstHead;
               
                
            }else{
                 second.next=null;
                first.next=secondHead;
            }
            return firstHead;
            
        }
    

Log in to reply
 

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