class Stack {
constructor() {
this.dataStack = []
this.miniStack = []
}
push(num) {
if(this.dataStack.length === 0) {
this.dataStack.push(num)
this.miniStack.push(num)
} else {
this.dataStack.push(num)
if (num < this.miniStack[this.miniStack.length - 1]) {
this.miniStack.push(num)
} else {
this.miniStack.push(this.miniStack[this.miniStack.length - 1])
}
}
}
pop() {
if(this.dataStack.length === 0) {
throw new Error('栈没有数据了')
}
this.miniStack.pop()
return this.dataStack.pop()
}
getMin() {
if(this.dataStack.length === 0) {
throw new Error('栈没有数据了')
}
return this.miniStack[this.miniStack.length-1]
}
}
var stack = new Stack()
stack.push(5)
stack.push(4)
stack.push(3)
stack.push(6)
stack.push(2)
stack.push(8)
console.log(stack.getMin()) //2
stack.pop()
console.log(stack.getMin()) //2
stack.pop()
console.log(stack.getMin()) //3