Skip to content

Latest commit

 

History

History
44 lines (36 loc) · 1018 Bytes

栈.md

File metadata and controls

44 lines (36 loc) · 1018 Bytes

栈是一种受限的线性表,也可以看作是递归的一种实现结构。后进先出(LIFO)。其限制只能在栈的一端对栈进行插入,删除。这一端称为栈顶,而末端称为栈底

function Stack() {
  this.items = [];

  // 压栈
  Stack.prototype.push = function(element) {
    this.items.push(element);
  };

  // 从栈中取出
  Stack.prototype.pop = function() {
    return this.items.pop();
  };

  // 查看栈顶元素
  Stack.prototype.peek = function() {
    return this.items[this.items.length - 1];
  };

  // 判断栈是否为空
  Stack.prototype.isEmpty = function() {
    return this.items.length === 0;
  };

  // 获取栈中元素的个数
  Stack.prototype.size = function() {
    return this.items.length;
  };

  // toString方法
  Stack.prototype.toString = function() {
    var resultStr = "";
    for (let i = 0; i < this.items.length; i++) {
      resultStr += i;
    }
    return resultStr;
  };
}

const list = new Stack();