一道js编程题:用js实现栈的出栈,入栈等操作

这是4月份快手前端实习笔试的一道编程题,要求是实现:

入栈:NumberStack.push(num) 、出栈:NumberStack.pop() 、找出栈中第n大的数:NumberStack.max(n)

//下面是我的版本
function NumberStack() {
  this.stack = []; //栈的定义
}

NumberStack.prototype.push = function (num) {
  if (typeof num != "number") return false;
  this.stack.push(num);
};

NumberStack.prototype.pop = function () {
  if(this.stack.length>0){
    let last = this.stack.pop();
    return last;
  }
};

NumberStack.prototype.max = function (n) {
  let newArr = [].concat(this.stack);
  return newArr.sort()[n-1];
};

另外下面是在牛客网上另一个朋友写的,我觉得比我得要好一些

function NumberStack(){
    this.stack=[];//存储栈
    this.maxStack=[];//辅助栈,从小到大的排序
}
NumberStack.prototype.push=function(num){
    if(Object.prototype.toString.call(num)!="object Number") return false; 
    this.stack.push(num); 
    if(!this.maxStack.length){ 
        this.maxStack.push(num);
    }else{
        let len=his.maxStack.length;
        for(let i=0;i<len;i++){
            if(num<this.maxStack[i]){
                this.maxStack.splice(i,0,num);//将num插入maxStack到合适的位置
                break; 
            }
        }
    }
} 
NumberStack.prototype.pop=function(){ 
    let num=this.stack.pop();
    this.maxStack.splice(this.maxStack.indexOf(num),1);//将num从maxStack中删除 
    return num;
}

NumberStack.prototype.max=function(n){ 
    if(n<1||n>this.maxStack.length) return false; 
    return this.maxStack[this.maxStack.length-n];
}

猜你喜欢

转载自blog.csdn.net/qq_34305040/article/details/80256486