49 lines
1.2 KiB
JavaScript
49 lines
1.2 KiB
JavaScript
const MinStack = function () {
|
|
this.data = []; // 内部使用数组维护栈元素
|
|
this.minstack = [Infinity]; // 利用栈结构维护最小元素
|
|
};
|
|
|
|
/**
|
|
* @param {number} val
|
|
* @return {void}
|
|
*/
|
|
MinStack.prototype.push = function (val) {
|
|
// 判断当前插入的元素是否比栈的最小元素还小
|
|
if (val < this.minstack[this.minstack.length - 1]) this.minstack.push(val);
|
|
this.data.push(val);
|
|
};
|
|
|
|
/**
|
|
* @return {void}
|
|
*/
|
|
MinStack.prototype.pop = function () {
|
|
// 判断栈顶的元素是否是最小元素,如果是,最小元素栈顶的元素也要删除
|
|
if (this.data[this.data.length - 1] === this.minstack[this.minstack.length - 1]) {
|
|
this.minstack.pop();
|
|
}
|
|
if (this.data.length) this.data.pop();
|
|
};
|
|
|
|
/**
|
|
* @return {number}
|
|
*/
|
|
MinStack.prototype.top = function () {
|
|
if (this.data.length) return this.data[this.data.length - 1];
|
|
};
|
|
|
|
/**
|
|
* @return {number}
|
|
*/
|
|
MinStack.prototype.getMin = function () {
|
|
return this.minstack[this.minstack.length - 1];
|
|
};
|
|
|
|
/**
|
|
* Your MinStack object will be instantiated and called as such:
|
|
* var obj = new MinStack()
|
|
* obj.push(val)
|
|
* obj.pop()
|
|
* var param_3 = obj.top()
|
|
* var param_4 = obj.getMin()
|
|
*/
|