-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist_partition.java
99 lines (80 loc) · 2.87 KB
/
list_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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
public class MyList {
private final class MyListNode {
int value;
MyListNode next;
MyListNode(int value) {
this.value = value;
}
}
private MyListNode head;
private MyListNode tail;
public void add(int value) {
MyListNode newnode = new MyListNode(value);
if (tail == null) {
head = newnode;
} else {
tail.next = newnode;
}
tail = newnode;
}
public void partition(int pivot) {
MyListNode smallListHead = null;
MyListNode smallListTail = null;
MyListNode largeListHead = null;
MyListNode largeListTail = null;
while (head != null) {
// Remove the head node H:
MyListNode currentNode = head;
head = head.next;
// Decide to which of the two lists to append the node H:
if (currentNode.value < pivot) {
if (smallListTail == null) {
smallListHead = currentNode;
} else {
smallListTail.next = currentNode;
}
smallListTail = currentNode;
} else {
if (largeListTail == null) {
largeListHead = currentNode;
} else {
largeListTail.next = currentNode;
}
largeListTail = currentNode;
}
}
if (smallListHead == null) {
head = largeListHead;
} else if (largeListHead == null) {
head = smallListHead;
} else {
head = smallListHead;
smallListTail.next = largeListHead;
tail = largeListTail;
// Marks the end of the list, otherwise might be a cycle:
largeListTail.next = null;
}
}
public String toString() {
StringBuilder sb = new StringBuilder().append('[');
String separator = "";
for (MyListNode node = head; node != null; node = node.next) {
sb.append(separator).append(node.value);
separator = ", ";
}
return sb.append(']').toString();
}
public static void main(String[] args) {
MyList list = new MyList();
list.add(3);
list.add(5);
list.add(8);
list.add(5);
list.add(1);
list.add(10);
list.add(2);
System.out.println(list);
list.partition(5);
System.out.println(list);
}
}