js数据结构--栈

7 阅读1分钟

Date: 2020-06-26

前面介绍了列表,它是一种最自然的数据组织方式,如果对数据的存储顺序要求不重要,那么列表就是一种非常适合的数据结构。但对于计算机其他的一些应用(比如后缀表达式),那么列表就显得有些无能为力, 所以,我们需要一种和列表功能相似但更复杂的数据结构。

栈(Stack)

栈,又称堆栈,和列表类似。栈内元素只能通过列表的一段访问,数据只能在栈顶添加或删除,遵循 先入后出(LIFO,last-in-first-out)的原则。

function Stack() {
  this.dataStore = []     // 初始化空数组来保存列表元素
  this.size = 0           // 初始化元素个数为0

  this.push = push        // 入栈
  this.pop = pop          // 出栈
  this.peek = peek        // 查看栈顶元素
  this.clear = clear      // 清空栈
}

接下来实现这些方法:

push: 入栈

function push(el) {
  this.dataStore[this.size++] = el
}

pop: 出栈

function pop() {
  return this.dataStore[--this.size]
}

peek: 查看栈顶元素

function peek() {
  if (!this.size) return null
  return this.dataStore[this.size - 1]
}

clear: 清空栈

function clear() {
  delete this.dataStore
  this.dataStore = []
  this.size = 0
}

完整代码

function Stack() {
  this.dataStore = []     // 初始化空数组来保存列表元素
  this.size = 0           // 初始化元素个数为0

  this.push = push        // 入栈
  this.pop = pop          // 出栈
  this.peek = peek        // 查看栈顶元素
  this.clear = clear      // 清空栈
}

function push(el) {
  this.dataStore[this.size++] = el
}

function pop() {
  return this.dataStore[--this.size]
}

function peek() {
  if (!this.size) return null
  return this.dataStore[this.size - 1]
}

function clear() {
  delete this.dataStore
  this.dataStore = []
  this.size = 0
}

参考:简书 JS中的算法与数据结构——栈(Stack)