数据结构_队列结构_优先级

五迷三道 提交于 2020-02-20 09:33:31
class priorityElement {
    constructor (elem, priority) {
      this.elem = elem
      this.priority = priority
    }
  }

  class priorityQueue {
    constructor () {
      this.items = []
    }
    enqueue (elem, priority) {
      let priorityElem = new priorityElement(elem, priority)
      let flag = true
      if (!this.isEmpty()) {
        for (let i = 0; i < this.size(); i++) {
          if (priorityElem.priority < this.items[i].priority) {
            flag = false
            this.items.splice(i, 0, priorityElem)
            break;
          }
        }
        if (flag) this.items.push(priorityElem)
      }else {
        this.items.push(priorityElem)
      }
    }

    isEmpty () {
      return this.items.length <= 0
    }
    size () {
      return this.items.length
    }
  }
  var person = new priorityQueue()
  person.enqueue('a', 10)
  person.enqueue('b', 8)
  person.enqueue('c', 3)
  person.enqueue('d', 9)
  person.enqueue('e', 4)
  person.enqueue('f', 2)
  person.enqueue('g', 5)
  person.enqueue('h', 11)
  console.log(person)

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!