forked from jmcilhargey/cracking-the-coding-interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchpt2-partition.js
More file actions
36 lines (33 loc) · 1.04 KB
/
chpt2-partition.js
File metadata and controls
36 lines (33 loc) · 1.04 KB
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
function partitionListAroundValue(headNode, pivotValue) {
// Nodes < pivotValue need to come before nodes >= pivotValue
var currentNode = headNode;
var smallerList = null;
var smallerListStart = null;
var largerList = null;
var largerListStart = null;
while (currentNode) {
var nextNode = currentNode.next;
if (currentNode.value < value) {
// Smaller so add to smaller list
if (smallerList === null) {
smallerList = currentNode;
smallerListStart = currentNode;
} else {
smallerList.next = currentNode;
}
} else {
// Larger or equal add to bigger list
if (largerList === null) {
largerList = currentNode;
largerListStart = currentNode;
} else {
largerList.next = currentNode;
}
}
currentNode = nextNode;
}
// Now we stitch together the two lists since we tracked the end of smaller list and start of bigger list
smallerList.next = largerListStart;
// Retrieve the head of the new list
return smallerListStart;
}