美文网首页
队列的优先级

队列的优先级

作者: 海蒂Hedy | 来源:发表于2019-11-18 09:35 被阅读0次
function Queue() {
                //属性
                this.item = []
                //方法
                //1.将元素加入队列出
                Queue.prototype.enqueue = function (element) {
                    this.item.push(element)
                }
                Queue.prototype.dequeue = function () {
                    return this.item.shift()
                }
                //2.从队列中删除前端数据
                Queue.prototype.front = function () {
                    return this.item[0]
                }
                //3.查看队列是否为空
                Queue.prototype.isEmpty = function () {
                    return this.item.length == 0
                }
                //4.查看队列中元素的个数
                Queue.prototype.size = function () {
                    return this.item.length
                }
                //5.toString
                Queue.prototype.toString = function () {
                    var resultString = ''
                    for (var i = 0; i < this.item.length; i++) {
                        resultString += this.item[i] + ''
                    }
                    return resultString
                }

            }
        //封装队列优先级
        function PriorotyQueue(){
            //从新创建一个类,理解成内部类
            function QueueElement(element,priority){
                this.element = element
                this.priority = priority
            }

            //封装属性
            this.items = []
            //实现插入方法
            PriorotyQueue.prototype.enqueue = function(element,priority){
                //1.创建对象
                var queueElement = new QueueElement(element,priority)
                //2.判断队列是否为空
                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)
                    }
                }
            }
        }

更多链接:https://github.com/codprincess/AdayJS

相关文章

网友评论

      本文标题:队列的优先级

      本文链接:https://www.haomeiwen.com/subject/rurvictx.html