题目
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
思路
增加了一个辅助栈,每次压入数据栈时,把当前栈里面最小的值压入辅助栈当中,使得当前栈内最小的数据始终在辅助栈的栈顶。
代码
const stack = [],
minStack = [];
let tmp = null;
function push(node) {
if (tmp !== null) {
if (tmp > node) {
tmp = node;
}
stack.push(node);
minStack.push(tmp);
} else {
tmp = node;
stack.push(node);
minStack.push(tmp);
}
}
function pop() {
stack.pop();
minStack.pop();
}
function top() {
return stack[stack.length - 1];
}
function min() {
return minStack[minStack.length - 1];
}