Easy-understanding Java solution


  • 0
    Y
    public ListNode partition(ListNode head, int x) {
        ListNode lh = new ListNode(Integer.MAX_VALUE);
        ListNode rh = new ListNode(Integer.MAX_VALUE);
        ListNode li = new ListNode(Integer.MAX_VALUE);
        ListNode ri = new ListNode(Integer.MAX_VALUE);
        ListNode i = head;
        
        while(i != null){
            if(i.val < x){
                if(lh.next == null) {li = i; lh.next = li;}
                else{
                    li.next = i;
                    li = li.next;
                }
            }else{
                if(rh.next == null) {ri = i; rh.next = ri;}
                else{
                    ri.next = i;
                    ri = ri.next;
                }
            }
            i = i.next;
        }
        
        ri.next = null;
        
        li.next = rh.next;
        return lh.next == null ? rh.next : lh.next;
    }

Log in to reply
 

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