码迷,mamicode.com
首页 > 其他好文 > 详细

优先级队列封装

时间:2020-05-26 01:19:35      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:bsp   get   his   console   查看   for   enqueue   代码   nbsp   

// 封装优先级队列
        function PriorityQueue() {
            function QueueElement(element, priority) {
                this.element = element
                this.priority = priority
            }
            // 封装属性
            this.items = []
            //1. 实现插入方法
            PriorityQueue.prototype.enqueue = function (element, priority) {
                // 1.创建QueueElement对象
                let queueElement = new QueueElement(element, priority)
                // 2.判断队列是否为空
                console.log(this.items)
                if (this.items.length == 0) {
                    this.items.push(queueElement)
                } else {
                    let added = false
                    for (let i = 0; i < this.items.length; i++) {
                        if (queueElement.priority < this.items[i].priority) {
                            this.items.splice(i, 0, queueElement)
                            console.log(this.items)
                            added = true
                            break
                        }
                    }
                    if (!added) {
                        this.items.push(queueElement)
                    }
                }
            }
            //2. 从队列中删除前元素
            PriorityQueue.prototype.dequeue = ((element, priority) => {
                return this.items.shift()
            })
            //3. //3.查看前端的元素
            PriorityQueue.prototype.front = () => {
                return this.items[0];
            }
            //4.查看队列是否为空
            PriorityQueue.prototype.isEmpty = () => {
                return this.items.length == 0;
            }
            //5.查看队列中的元素个数
            PriorityQueue.prototype.size = () => {
                return this.items.length;
            }
            //6.toString方法
            PriorityQueue.prototype.toString = () => {
                let getString = "";
                for (let i = 0; i < this.items.length; i++) {
                    getString += this.items[i].element + " ";
                }
                return getString;
            }
        }
        // 测试代码
        let pq = new PriorityQueue()
        pq.enqueue("a", 1)
        pq.enqueue("b", 3)
        pq.enqueue("c", 2)
        console.log(pq.items)

 

优先级队列封装

标签:bsp   get   his   console   查看   for   enqueue   代码   nbsp   

原文地址:https://www.cnblogs.com/jwzhang/p/12961896.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!