zoukankan      html  css  js  c++  java
  • js封装一个优先级队列

    // 基于数组封装一个优先级队列
    function PriorityQueue(){
        this.items = [];
        // 创建一个内部类,用于存放元素的内容和优先级
        function QueueElement(element,priority){
            this.element = element;
            this.priority = priority;
        }
        // 插入方法
        PriorityQueue.prototype.entryQueue = function(ele,pri){
            let element = new QueueElement(ele,pri);
            if(!this.items.length){
                return this.items.push(element)
            }
            let isAdd = false;  // 用于判断是否在优先级比较当中插入了
            for(let i = 0; i < this.items.length; i++){
                if(element.priority < this.items[i].priority){
                    this.items.splice(i,0,element);
                    isAdd = true;
                    break
                }
            }
            if(!isAdd){
                return this.items.push(element)
            }
        }
        // 数据出队列
        PriorityQueue.prototype.outQueue = 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 str = '';
            for (let i = 0; i < this.items.length; i++) {
                str += this.items[i].element + '-' + this.items[i].priority + ' '
            }
            return str
        }
    }
    
    let pq = new PriorityQueue();
    pq.entryQueue('一般顾客',1000)
    pq.entryQueue('二级顾客',500)
    pq.entryQueue('vip顾客',100)
    pq.entryQueue('svip顾客',10)
    console.log(pq);
    console.log(pq.toString()); // svip顾客-10 vip顾客-100 二级顾客-500 一般顾客-1000 
  • 相关阅读:
    让用户舒服起来 10个改善UI的技术
    Powerpoint快捷键大全
    自制Flash FLV视频播放器
    Firefox与IE在CSS样式表中的差异
    让你每天都充满积极性的五个方法
    asp.net 2实用技术汇总
    春季要健康 “排毒”三步走
    皮肤变好必遵守洗脸九法
    经典博客收集
    教你一招让网页用上漂亮的11PX中文字体
  • 原文地址:https://www.cnblogs.com/cyf666cool/p/14837148.html
Copyright © 2011-2022 走看看