-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathproblem_208.js
70 lines (60 loc) Β· 1.32 KB
/
problem_208.js
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
/**
* ListNode Definition
* @param {*} val
* @constructor
*/
function ListNode(val) {
this.val = val;
this.next = null;
}
/**
* Partitions a Linked List so nodes < k are on the left
* Time Complexity: O(n)
* @param {ListNode} head
* @param {ListNode} k
* @return {ListNode}
*/
function partitionList(head, k) {
if (!head || k < 0) return null;
let lessThan = new ListNode();
let greaterThan = new ListNode();
const lessRunner = lessThan;
const greaterRunner = greaterThan;
let runner = head;
while (runner) {
if (runner.val < k) {
lessThan.next = runner;
lessThan = lessThan.next;
} else {
greaterThan.next = runner;
greaterThan = greaterThan.next;
}
runner = runner.next;
}
lessThan.next = greaterRunner.next;
return lessRunner.next;
}
/* EXAMPLE */
const a = new ListNode(5);
const b = new ListNode(1);
const c = new ListNode(8);
const d = new ListNode(0);
const e = new ListNode(3);
a.next = b;
b.next = c;
c.next = d;
d.next = e;
let curr = a;
let list = '';
while (curr.next) {
list += `${curr.val} -> `;
curr = curr.next;
}
console.log(`${list}${curr.val}`); // 5 -> 1 -> 8 -> 0 -> 3
curr = partitionList(a, 3);
list = '';
while (curr.next) {
list += `${curr.val} -> `;
curr = curr.next;
}
console.log(`${list}${curr.val}`); // 1 -> 0 -> 5 -> 8 -> 3