【JS数据结构】优先级队列

直接上代码
类里面再封装一个类 用于传入队列 以及 优先级
优先级队列—> 每个队列都带有一个优先级 可以理解为钱包 谁的钱多谁优先 类似与头等舱等
function PriorityQueue() {
  function QueueElement(element, priority) {
    this.element = element;
    this.priority = priority;
  }
  //封装属性
  this.items = [];
  PriorityQueue.prototype.enqueue = function (element, priority) {
    var queueElement = new QueueElement(element, priority);
    if (this.items.length == 0) {
      this.items.push(queueElement);
    } else {
      var add = false;
      for (let i = 0; i < this.items.length; i++) {
        if (queueElement.priority < this.items[i].priority) {
          this.items.splice(i, 0, queueElement);
          add = true;
          break;
        }
      }
      if (!add) {
        this.items.push(queueElement);
      }
    }
  };
  PriorityQueue.prototype.dequeue = function () {
    this.items.shift();
  };
  PriorityQueue.prototype.front = function () {
    return this.items[0];
  };
  PriorityQueue.prototype.isEmpty = function () {
    return this.items.length == 0;
  };
  PriorityQueue.prototype.size = function () {
    return this.items.length;
  };
  PriorityQueue.prototype.toString = function () {
    var str = '';
    for (let i = 0; i < this.items.length; i++) {
      str += this.items[i].element +  + this.items[i].priority + '---';
    }
    return str;
  };
}

var pq = new PriorityQueue();

pq.enqueue('abc', 11);
pq.enqueue('cba', 111);
pq.enqueue('ad', 6);
pq.enqueue('abcd', 60);

console.log(pq.toString()); //ad6---abc11---abcd60---cba111--- 

你可能感兴趣的:(javascript,数据结构,vue.js)