-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathgetMaxStack.js
More file actions
53 lines (45 loc) · 914 Bytes
/
Copy pathgetMaxStack.js
File metadata and controls
53 lines (45 loc) · 914 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
47
48
49
50
51
52
53
class Stack {
constructor() {
this.items = [];
}
push(item) {
this.items.push(item);
}
pop() {
// if the stack is empty, return null
// (it would also be reasonable to throw an exception)
if (!this.items.length) {
return null;
}
return this.items.pop();
}
peek() {
if (!this.items.length) {
return null;
}
return this.items[this.items.length - 1];
}
}
class GetMaxStack {
constructor() {
this.stack = new Stack();
this.maxesStack = new Stack();
}
push(item) {
this.stack.push(item);
if (!this.maxesStack.peek() || item >= this.maxesStack.peek()) {
this.maxesStack.push(item);
}
}
pop() {
var item = this.stack.pop();
if (item === this.maxesStack.peek()) {
this.maxesStack.pop();
}
return item;
}
getMax() {
return this.maxesStack.peek();
}
}
export default GetMaxStack;