56 阅读1分钟

栈是一种“操作受限”的线性表,只允许在一端插入和删除数据。 我第一次接触这种数据结构的时候,就对它存在的意义产生了很大的疑惑。因为我觉得,相比数组和链表,栈带给我的只有限制,并没有任何优势。那我直接使用数组或者链表不就好了吗?为什么还要用这个“操作受限”的“栈”呢?事实上,从功能上来说,数组或链表确实可以替代栈,但你要知道,特定的数据结构是对特定场景的抽象,而且,数组或链表暴露了太多的操作接口,操作上的确灵活自由,但使用时就比较不可控,自然也就更容易出错。

class stack{
  constructor(n){
    this.count = 0;
    this.n = n;
    this.items = new Array(n).fill(0);
  }
  push(item){
    if (this.count >= this.n){
      return false;
    }
    this.items[this.count] = item;
    this.count++;
    return true;
  }
  pop(){
    if (this.count == 0 ){
      return null;
    }
    let item = this.items[this.count-1];
    this.count--;
    return item;
  }
}