一、栈构造函数
实现的方法:push(入栈)、pop(出栈)、top(查看栈顶)、isEmpty(是否为空)、clear(清空)、count(栈元素数量)
function Stack() { const items=[]; //入栈 this.push=function (item) { items.push(item) }; //出栈 this.pop=function () { return items.pop() }; //查看栈顶 this.top=function () { return items[items.length-1] }; //栈是否为空 this.isEmpty=function () { return 0===items.length }; //清空栈 this.clear=function () { items.splice(0,items.length) }; //栈数量 this.count=function () { return items.length } }
二、实现一个min方法,查看栈中最小的项,算法复杂度必须为O(1)
const mainStack=new Stack(); const supportStack=new Stack(); function getMin() { //主栈和辅助栈同时压入 //如果辅助栈不为空且压入的数字比辅助栈顶的值大,辅助栈继续压入一个栈顶元素 //否则就同时压入栈 this.push=function (value) { if(!supportStack.isEmpty() && supportStack.top()<=value){ mainStack.push(value); supportStack.push(supportStack.top()); }else{ mainStack.push(value); supportStack.push(value); } }; this.minValue=function () { return supportStack.pop(); } }