java 1ms with comment, sort of clean.


  • 0
    public ListNode partition(ListNode head, int x) {
            if (head == null)
                return head;
            // remember to initialize the local var.
            ListNode i = null, j = null, k = head;
            while (k != null) {
                if (k.val < x) {
                    if (i == null) { 
                        // the first node that has val < x
                        i = k;
                        if (j != null) { 
                            // this node is not the first node.
                            j.next = k.next;
                            k = k.next;  // don't move it to outside of if condition.
                            i.next = head;
                        } else { 
                            // this node is the fist node.
                            j = k;
                            k = k.next;
                        }
                        head = i;
                    } else { 
                        if (i == j) { 
                            // all nodes precedes j, inclusive, have val < x, thus i, j are identical.
                            j = k;
                            i = j;
                            k = k.next;
                        } else {
                            // i and j are not same, so consider seperately.
                            ListNode tmp = i.next;
                            j.next = k.next;
                            i.next = k;
                            i = k;
                            k = k.next;
                            i.next = tmp;
                        }
                    }
                } else {
                    // move the node to the next.
                    j = k;
                    k = k.next;
                }
            }
            
            return head;
        }
    '''

Log in to reply
 

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