Friday, November 6, 2015

[leetcode] Partition List

Use two dummy list standing for less than and greater or equal to

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode less = new ListNode(-1);
        ListNode greatEq = new ListNode(-1);
        ListNode currentLess = less, currentGeq = greatEq;
        while (head != null){
            ListNode next = head.next;
            head.next = null;
            if (head.val < x){
                currentLess.next = head;
                currentLess = head;
            }else{
                currentGeq.next = head;
                currentGeq = head;
            }
            head = next;
        }
        if (currentLess == less){
            return greatEq.next;
        }
        currentLess.next = greatEq.next;
        return less.next;
    }
}

No comments:

Post a Comment