-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2_min_max_stack.js
67 lines (52 loc) · 1.16 KB
/
2_min_max_stack.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
class Node {
constructor(val) {
this.value = val;
this.next = null;
this.nextMax = null;
this.nextMin = null;
}
}
class MinMaxStack {
constructor() {
this.top = null;
this.bottom = null;
this.length = 0;
}
push(val) {
const newNode = new Node(val);
if (!this.max() || val > this.max().value) newNode.nextMax = newNode;
else newNode.nextMax = this.max();
if (!this.min() || val < this.min().value) newNode.nextMin = newNode;
else newNode.nextMin = this.min();
if (!this.top) {
this.top = newNode;
this.bottom = newNode;
} else {
const temp = this.top;
this.top = newNode;
this.top.next = temp;
}
return ++this.length;
}
pop() {
if (!this.top) return null;
const node = this.top;
if (this.top === this.bottom) this.bottom = null;
this.top = this.top.next;
this.length--;
return node;
}
size() {
return this.length;
}
min() {
if (!this.top) return null
else return this.top.nextMin;
}
max() {
if (!this.top) return null
else return this.top.nextMax;
}
}
exports.Node = Node;
exports.MinMaxStack = MinMaxStack;