-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.js
More file actions
46 lines (39 loc) · 931 Bytes
/
Copy pathsolution.js
File metadata and controls
46 lines (39 loc) · 931 Bytes
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
/* Structure of linked list node
class Node{
constructor(data){
this.data = data;
this.next = null;
}
}
*/
class Solution {
// Reverse linked list
reverseList(head) {
let prev = null;
let curr = head;
while (curr) {
let nextNode = curr.next; // save next node
curr.next = prev; // reverse link
prev = curr; // move prev
curr = nextNode; // move curr
}
return prev;
}
compute(head) {
// Reverse the list
head = this.reverseList(head);
let maxSoFar = head.data;
let curr = head;
while (curr && curr.next) {
// Remove node if smaller than maxSoFar
if (curr.next.data < maxSoFar) {
curr.next = curr.next.next;
} else {
curr = curr.next;
maxSoFar = curr.data;
}
}
// Restore original order
return this.reverseList(head);
}
}