forked from maiquynhtruong/algorithms-and-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpartition.java
39 lines (35 loc) · 1.14 KB
/
partition.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class Solution {
public static void partition(ListNode cur, int x) {
ListNode before = new ListNode();
ListNode after = new ListNode();
ListNode bPointer = before, aPointer = after;
ListNode xNode = null;
while (cur != null) {
if (cur.val == x) xNode = cur;
else if (cur.val < x) { bPointer.next = cur; bPointer = bPointer.next; }
else {aPointer.next = cur; aPointer = aPointer.next; }
cur = cur.next;
}
if (xNode != null) { bPointer.next = xNode; bPointer = bPointer.next; }
bPointer.next = after;
return before;
}
public static void PartitionShorter(ListNode head, int x) {
ListNode cur = head, tail;
while (cur != null) {
ListNode curNext = cur.next;
if (cur.val < x) {
cur.next = head;
head = cur;
} else {
tail.next = cur;
tail = cur;
}
cur = curNext;
}
tail.next = null;
return head;
}
public static void main(String args[]) {
}
}