栈JS实现

Posted by HandsomeWalker on June 17, 2020

栈特点

入栈出栈速度很快,先进后出,能用递归实现的场景,都能使用迭代加栈来实现

构造栈

JS中的数组同时具备栈和队列的特性

function Stack() {
  this.dataStore = [];
  this.length = 0;
  this.top = 0;
}
Stack.prototype = {
  push(data) {
    this.dataStore[this.top++] = data;
    this.length++;
  },
  pop() {
    if (this.top === 0) {
      return undefined;
    }
    this.length--;
    return this.dataStore[--this.top];
  },
  peek() {
    return this.dataStore[this.top - 1];
  },
  clear() {
    this.top = 0;
  }
}

测试

var s = new Stack();
s.push(1);
s.push(2);
s.pop();
s.push(3);
console.log(s.length);
console.log(s.peek());
s.clear();
console.log(s.peek());