美文网首页
JavaScript数据结构之队列

JavaScript数据结构之队列

作者: 27亿光年中的小小尘埃 | 来源:发表于2020-04-09 23:19 被阅读0次
    class Queue{
      constructor() {
        this.count = 0
        this.list = {}
        this.lowestCount=0
      }
      //往队列添加元素
      enqueue (element) {
        this.list[this.count] = element
        this.count++
      }
      //检测队列是否为空
      isEmpty () {
        return this.count-this.lowestCount===0
      }
      //从队列里移除元素
      dequeue () {
        if (this.isEmpty()) {
          return undefined
        }
        const result = this.list[this.lowestCount]
        delete this.list[this.lowestCount]
        this.lowestCount++
        return result
      }
      //查看队列头元素
      peek () {
        if (this.isEmpty()) {
          return undefined
        }
        return this.list[this.lowestCount]
      }
      //获取队列长度
      size () {
        return this.count - this.lowestCount 
      }
      //清空队列
      clear () {
        this.list = {}
        this.count = 0
        this.lowestCount=0
      }
      //字符串方法
      toString () {
        if (this.isEmpty()) {
          return ''
        }
        let str = `${this.list[this.lowestCount]}`
        for (let i = this.lowestCount + 1; i < this.count; i++){
          str+=`,${this.list[i]}`
        }
        return str
      }
      //
    }
    

    相关文章

      网友评论

          本文标题:JavaScript数据结构之队列

          本文链接:https://www.haomeiwen.com/subject/woukmhtx.html