-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMinStack.js
More file actions
52 lines (44 loc) · 795 Bytes
/
MinStack.js
File metadata and controls
52 lines (44 loc) · 795 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
/**
* initialize your data structure here.
*/
const MinStack = function () {
this.stack = []
}
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function (x) {
const min = (this.stack.length === 0)
? x
: Math.min(x, this.getMin())
this.stack.push({
value: x,
min: min
})
}
/**
* @return {void}
*/
MinStack.prototype.pop = function () {
this.stack.pop()
}
/**
* @return {number}
*/
MinStack.prototype.top = function () {
if (this.stack.length === 0) {
return undefined
}
return this.stack[this.stack.length - 1].value
}
/**
* @return {number}
*/
MinStack.prototype.getMin = function () {
if (this.stack.length === 0) {
return undefined
}
return this.stack[this.stack.length - 1].min
}
module.exports = MinStack