Monday, December 8, 2014

Partition List LeetCode

Create two listnodes for each list.

 public ListNode partition(ListNode head, int x) {
        ListNode root = new ListNode(-1);
        ListNode pivot = new ListNode(x);
       
        ListNode before = root;
        ListNode after = pivot;
       
        ListNode curr = head;
       
        while (curr != null) {
            ListNode next = curr.next;
            if (curr.val < x) {
                before.next = curr;
                before = curr;
            } else {
                after.next = curr;
                after = curr;
                after.next = null;
            }
            curr = next;
        }
        before.next = pivot.next;
        return root.next;
    }

No comments:

Post a Comment