Js实现优先队列

本文介绍了如何使用JavaScript实现优先级队列,通过创建QueueElement构造函数封装元素和优先级,然后在enqueue方法中根据优先级动态插入元素,保持队列的优先级顺序。同时提供了dequeue、front、isEmpty、size和toString等方法来操作和查看队列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Js实现优先队列

栈和堆基本是我们学习数据结构的必备关卡了,当你实现了堆结构以后尝试实现一下优先级队列吧!

一下是我的优先级队列代码结构-----狗尾续貂

 function PriorityQueue() {
      // 创建一个保存数据的对象
      this.items = [];
      // 由于我们现在是两个元素所以我们需要把这两个元素进行一次封装这里我们也使用构造函数进行一次封装
      /*
      如果我们不进行封装我们很难区分那个对那个元素封装一下
       */
      function QueueElement(element, proiorty) {
        this.element = element;
        this.proiorty = proiorty;
      }
      PriorityQueue.prototype.enqueue = function (element, proiorty) {
        // 我们把接收过来的两个参数传入封装函数中封装一个对象
        var queueElement = new QueueElement(element, proiorty);
        //如果当前队列中没有元素的话我们就直接添加
        if (this.items.length == 0) {
          this.items.push(queueElement);
        } else {
          // 创建一个状态如果当前元素都比items里面的大我们就添加到最前面就行
          var flag = false;
          // 如果有元素我们需要判断一下
          //先遍历一下原有的元素进行全部比较一下
          for (var i = 0; i < this.items.length; i++) {
            // 判断一下当前元素的插入位置
            // 如果当前元素的proiorty大于堆中的某个元素proiorty我们需要把它放到他的前面
            if (queueElement.proiorty > this.items[i].proiorty) {
              //  splice--插入功能, 第一个参数(插入位置),第二个参数(0),第三个参数(插入的项)
              this.items.splice(i, 0, queueElement);
              flag = true;
              break;
            }
          }
          if (!flag) {
            this.items.push(queueElement);
          }
        }
      };
      // 从队列中删除元素
      PriorityQueue.prototype.dequeue = function () {
        return 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;
      };
      // toString方法
      PriorityQueue.prototype.toString = function () {
        let Stringresult = "";
        for (var i = 0; i < this.length; i++)
          [(Stringresult += this.items[i])];
        return Stringresult;
      };
    }

Test

 var pq = new PriorityQueue();
     pq.enqueue("d", 30);
     pq.enqueue("c", 50);
     pq.enqueue("a", 100);
     pq.enqueue("b", 60);
     pq.enqueue("e", 20);
     console.log(pq.items);

Result

0:QueueElement {element: 'a', proiorty: 100}
1:QueueElement {element: 'b', proiorty: 60}
2:QueueElement {element: 'c', proiorty: 50}
3:QueueElement {element: 'd', proiorty: 30}
4:QueueElement {element: 'e', proiorty: 20} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CoderJoon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值