-
Notifications
You must be signed in to change notification settings - Fork 2
/
PartitionList.java
56 lines (48 loc) · 1.22 KB
/
PartitionList.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package LinkedList._86_PartitionList;
import DataStructure.ListNode;
/**
* Created by hengwang on 2017-05-26.
*/
public class PartitionList {
/**
* Create two new linked list to store the left and right, then merge them into one.
*
* This approach is mostly "stable" in that elements stay in their original order, other than the necessary
* movement around the partition.
*
* @param head
* @param x
* @return
*/
public ListNode partition(ListNode head, int x) {
ListNode current = head;
ListNode leftStart = null, left = null, rightStart = null, right = null;
while (current != null) {
ListNode next = current.next;
current.next = null;
if (current.data < x) {
if (left == null) {
leftStart = current;
left = leftStart;
} else {
left.next = current;
left = left.next;
}
} else {
if (right == null) {
rightStart = current;
right = rightStart;
} else {
right.next = current;
right = right.next;
}
}
current = next;
}
if (leftStart == null) {
return rightStart;
}
left.next = rightStart;
return leftStart;
}
}