队列

先进先出数据结构;想一个管道,先进去的物品先出来。下面用javascript的数组方法模拟队列

1

let arr = []
arr.push(0)
arr.push(1)
console.log(arr) // [0, 1]
arr.shift()
console.log(arr) // [1]
arr.shift()
console.log(arr) // []
class Queue {
  constructor () {
    this.arr = []
  }
  push (item) {
    this.arr.push(item)
  }
  shift () {
    this.arr.shift()
  }
  peek () {
    return this.arr[0]
  }
}

相关leetcode题:

results matching ""

    No results matching ""