Straightforward one pass java solution


  • 0
    T
    public static ListNode partition(ListNode head, int x) {
        
        ListNode less = new ListNode(0);
        ListNode result = less;
        ListNode greater_or_equal = new ListNode(0);
        ListNode tempNode = greater_or_equal;
        
        while( head != null ){
            
            if( head.val < x ){
                less.next = head;
                less = less.next;
            }
            else{
                greater_or_equal.next = head;
                greater_or_equal = greater_or_equal.next;
            }
            head = head.next;
        }
        // Very important, to avoid looping. For instance, [2,1],2
        greater_or_equal.next = null;
        less.next = tempNode.next;
        
        return result.next;
    }

Log in to reply
 

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