86. Partition List

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,

Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode gt = new ListNode(-1);
        ListNode lt = new ListNode(-1);
        ListNode t1 = gt;
        ListNode t2 = lt;

        while(head != null){
            if(head.val < x){
                t2.next = head;
                t2 = t2.next;
            }else{
                t1.next = head;
                t1 = t1.next;
            }
            head = head.next;
        }

        t2.next = gt.next;
        t1.next = null;
        return lt.next;
    }
}

the following improvement won't work cause you are CREATING A new reference to the node ltail/mtail points to, then move it around, you are NOT REALLY MOVING ltail/mtail.


            ListNode tail = head.val < x ? ltail : mtail;
            tail.next = head;
            tail = tail.next;

results matching ""

    No results matching ""