题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
JS版本
let temp = [];
let temp2 = [];
function top()
{
if(temp.length > 0)
return temp[temp.length - 1];
return null;
}
function push(node)
{
let t = top();
if(!t || node < temp2[temp2.length - 1]){
temp.push(node);
temp2.push(node);
}else if(node >= temp2[temp2.length - 1]){
temp.push(node);
}
}
function pop()
{
let t = top();
if(t === temp2[temp2.length - 1]){
temp.length--;
temp2.length--;
}else{
temp.length--;
}
}
function min()
{
return temp2[temp2.length - 1]
}