数据结构-javascript实现【 栈 】

栈是一种遵从后进先出(LIFO) 原则的有序集合。新添加的或待删除的元素都保存在栈的末尾,称作栈顶,另一端叫做栈底。

1. 栈所拥有的职责方法

 push(element): 添加一个元素到栈顶

 pop(): 移除栈顶的元素

 peek(): 返回栈顶的元素

 clear(): 清空栈里的元素

 isEmpty(): 检测栈是否为空

 size(): 返回栈的元素个数

2. 栈的实现

class Stack {
  constructor(){
    this.items = [];
  }

  push(element) {
    this.items.push(element);
  }

  pop() {
    return this.items.pop();
  }

  peek() {
    return this.items[this.items.length-1];
  }

  isEmpty() {
    return this.items.length == 0;
  }

  size() {
    return this.items.length;
  }

  clear() {
    this.items = [];
  }

  print() {
    console.log(this.items.toString());
  }
}
const stack = new Stack();
stack.push(0);
stack.push(1);
stack.push(2);
const a = stack.peek();
console.log(a); //2
const b = stack.size();
console.log(b); //3
stack.print(); //0,1,2

 

 

 

posted @ 2021-11-22 11:33  箫笛  阅读(52)  评论(0)    收藏  举报