提问者:小点点

在JavaScript中实现堆栈有什么更好的方法吗? [已关闭]


我对堆栈的实现如下:

 var Stack = (function () {
  function Stack() {
    this.stack = [];
    this.top = 0;
  }

  var _proto = Stack.prototype;
  _proto.push = function push(val) {
    this.stack[this.top] = val;
    return ++this.top;
  };

  _proto.pop = function pop() {
    if (this.top === 0) throw new Error("stack is empty");
    this.top--;
    let result = this.stack[this.top];
    this.stack = this.stack.splice(0, this.top);
    return result;
  };

  _proto.size = function size() {
    return this.top;
  };

  _proto.peek = function peek() {
    if (this.top === 0) throw new Error("stack is empty");
    return this.stack[this.top];
  };

  return Stack;
})();

请提出一些改进建议。 在pop中,我可以使用Splice以外的任何东西吗? 那么只递减top并允许JavaScript垃圾收集我们删除的top元素呢?


共1个答案

匿名用户

您也可以像这样制作.pop。 我想这会很容易

isEmpty函数将非常好。

function isEmpty() {
     return this.top === 0;
   }


function pop() {
    if( this.isEmpty() === false ) {
       this.top = this.top - 1;
       return this.stack.pop();
     }
   }