数据结构-堆栈篇

141 阅读1分钟

是一种遵循后入先出的数据集合,新添加的元素靠近栈顶,后添加靠近栈底

用对象模拟栈


  // 对象模拟 
  class Stack {
    constructor() {
      this.count = 0
      this.item = {}
    }

    push(value) {
      this.item[this.count] = value
      this.count++
    }

    peek() {
      if (this.isEmpty()) {
        return undefined
      }

      this.count--
      const result = this.item[this.count]
      delete this.item[this.count]

      return result
    }

    isEmpty() {
      return this.count === 0
    }

    size() {
      return this.count
    }

    print() {
      let str = this.item[0]

      for (let i = 1; i < this.count; i++) {
        str = `${str}=>${this.item[i]}`
      }

      return str
    }

    clear() {
      this.count = 0
      this.item = {}
    }
  }

用数组模拟栈


  //  数组模拟
  class Stack {
    constructor() {
      this.item = []
    }

    push(value) {
      this.item.push(value)
    }

    peek() {
      return this.item.pop()
    }

    isEmpty() {
      return !!this.item.length
    }

    size() {
      return this.item.length
    }

    print() {
      return this.item.join('=>')
    }

    clear() {
      this.item = []
    }
  }