研习算法(续三)-栈实现(javascript版)

98 阅读1分钟

栈简介

  • 一个后进先出的数据结构
  • javascript没有栈,可以用array数据结构模拟栈的功能

栈实现

  • size: 栈的大小
  • max: 栈的最大容量
  • sp: 栈指针
  • Stack Overflow: 栈溢出(异常)
  • Stack Underflow: 栈下溢(异常)

image.png

image.png

入栈示例

image.png

出栈示例(Stack Underflow)

image.png

入栈示例 (Stack Overflow)

image.png

image.png

image.png

出栈示例

image.png


class Stack {
  constructor(max = 1000) {
    this.max = max;
    this.sp = -1;
    this.data = Array.from({ length: max });
  }
  push(item) {
    if (this.sp === this.max - 1) {
      throw "Stack Overflow";
    }

    this.data[++this.sp] = item;
  }

  pop() {
    if (this.sp === -1) {
      throw "Stack Underflow";
    }

    return this.data[this.sp--];
  }
}
const stack = new Stack();

stack.push("a");
stack.push("b");
stack.push("c");
console.log(stack.pop());
console.log(stack.pop());

其他问题