数据结构与算法四(js 实现优先级队列)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>优先级队列</title>
</head>
<body>
<script>
    //封装优先级队列
    function priorityQueue(){
        function QueueElement(element,priority){
            this.element = element
            this.priority = priority
        }
        //1属性
        this.items = []

        priorityQueue.prototype.enQueue = function (element, priority) {
            //创建对象
            var qElement = new QueueElement(element,priority)
            //判断队列是否为空
            if(this.items.length == 0){
               this.items.push(qElement)
            }else {
                var added = false;
                for(var i = 0; i < this.items.length;i++){
                    if(qElement.priority < this.items[i].priority){
                        //插入到当前位置
                        this.items.splice(i,0,qElement)
                        added = true;
                        break;
                    }
                }
                if(!added){
                    this.items.push(qElement)
                }
            }
        }
        //2删除队列首元素
        priorityQueue.prototype.deQueue = function () {
            return this.items.shift()
        }
        //3查看队列前端元素
        priorityQueue.prototype.front = function () {
            return this.items[0]
        }
        //4查看队列是否为空
        priorityQueue.prototype.isEmpty = function () {
            return this.items.length == 0
        }
        //5查看队列元素个数
        priorityQueue.prototype.size = function () {
            return this.items.length
        }
        //6toString方法
        priorityQueue.prototype.toString = function () {
            var resultString = ''
            for(var i = 0; i < this.items.length; i++){
                resultString += this.items[i].priority + '-'+this.items[i].element + ' '
            }
            return resultString;
        }

    }
    //测试代码

    var pq = new priorityQueue();
    pq.enQueue('abc',11);
    pq.enQueue('a',22)
    pq.enQueue('b',10)
alert(pq)
</script>


</body>
</html>

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值