Skip to content

基本概念

栈的应用

  1. 函数调用栈 ECS
  2. 浏览器的历史记录

JS实现栈

javascript
class Stack {
  constructor() {
    this.items = [];
  }
  push(element) {
    this.items.push(element);
  }
  pop() {
    return this.items.pop();
  }
  // 查看栈顶元素
  peek() {
    return this.items[this.items.length - 1];
  }
  // 查看栈的长度
  size() {
    return this.items.length;
  }
  // 清空栈
  clear() {
    this.items = [];
  }
}

const demo = new Stack();

demo.push(1);
demo.push(2);
demo.push(3);
demo.push(4);
console.log(demo.peek());
console.log(demo.pop()); // 4
console.log(demo.pop()); // 3
console.log(demo.pop()); // 2
console.log(demo.pop()); // 1

made with ❤️ by ankang