优先级队列

文章详细描述了一个名为`priorityQueue`的类,实现了队列数据结构,包括enqueue(入队)、dequeue(出队)、front(查看队首元素)、isEmpty(检查队列是否为空)、size(获取元素数量)和toString(转换为字符串表示)。测试代码展示了如何使用这个优先级队列。
摘要由CSDN通过智能技术生成

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 added = false

                    for (var i = 0; i < this.items.length; i++) {

                        if (queueElement.priority < this.items[i].priority) {

                            this.items.splice(i, 0, queueElement)

                            added = true

                            break

                        }

                    }

                    if (!added) {

                        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

            }

            // 5. 查看元素中的个数

            priorityQueue.prototype.size = function () {

                return this.items.length;

            }

            // 6. toString

            priorityQueue.prototype.toString = function () {

                var resultString = '';

                for (var i = 0; i < this.items.length; i++) {

                    resultString += this.items[i].element + "-" + this.items[i].priority + " ";

                }

                return resultString;

            }

        };

        // 测试代码

        var pq = new priorityQueue();

        pq.enqueue('abc', 111);

        pq.enqueue('bweqw', 222);

        pq.enqueue('dede', 444);

        pq.enqueue('csaq3ew', 333);

        alert(pq.toString());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值