首页 > 一道 跟谁学 的笔试题,求解决。。。。

一道 跟谁学 的笔试题,求解决。。。。

请实现一个Stack(pop,push,size,clear);


var stack = {
    dataArr: [],
    pop: function() {
        var length = this.dataArr.length;
        if(length <= 0) {
            console.log('no data');
            return false;
        } else {
            var lastData = this.dataArr[length];
            this.dataArr.length = this.dataArr.length - 1;
            return lastData;
        }
    },
    push: function(data) {
        this.dataArr[this.dataArr.length+1] = data;
        return this.dataArr.length;
    },
    size: function() {
        return this.dataArr.length;
    },
    clear: function(){
        this.dataArr = [];
    }
}

//Stack类

function stack(){

this.dataStore = [];/*栈模拟数组*/
this.top = 0; /*记录当前栈顶的位置*/
this.push = push;
this.pop = pop;
this.clear = clear;
this.size = size;
}

function push(element){
   this.dataStore[this.top++] = element;
 }
   
function pop(element){
   return this.dataStore[--this.top];
 }
  
function clear(){
  this.top = 0 ;
 }
  
function size(){
  return this.top;
 } 
     
      
  

学生时代的题


JS 数组就可以作为一个 Stack,封装一下就可以。

function Stack(){
    this._data = [];
}
Stack.prototype={
    constructor:Stack,
    push:function (a){
        Array.prototype.push.apply(this._data,arguments);
    },
    pop:function (){
        Array.prototype.pop.apply(this._data,arguments);
    },
    size:function(){ return this._data.length;},
    clear:function(){ this._data.length=0;}
}

一个list或者数据就可以了。
ps:跟谁学是我的前个boss创建的,里面有不少我的老同事。

【热门文章】
【热门文章】