数据结构与算法2:用JavaScript 实现 队列 结构

队列 区别于 栈 的 【后进先出】 ,数据结构特点为 【先进先出】。用数组较易实现,本文为区别于栈结构,故封装 优先队列 ,即加入权重指标(权重越高,则优先输出)。

常用方法:

  • enqueue(element, priority) 插入元素
  • dequeue() 删除顶部队列元素
  • front() 查看队列顶部元素
  • isEmpty() 判断是否为空
  • size() 查看队列个数
  • toString() 方法
// 封装优先队列
function PriorityQueue(){
    // 新建一个队列元素的内部类
    function QueueElement(element, priority){
        this.element = element;
        this.priority = priority;
    }

    // 封装属性
    this.items = [];

    // 1 实现插入
    PriorityQueue.prototype.enqueue = function (element, priority){
        // 创建QueueElement对象
        var queueElement = new QueueElement(element, priority);

        // 判断队列是否为空,若为空则直接插入
        if(this.items.length === 0 ){
            this.items.push(queueElement);
        } else {
            let isContinue = true;
            for (var i = 0 ; i < this.items.length; i++){
                // 对比优先级,权重越高优先级越高
                if(queueElement.priority > this.items[i].priority){
                    this.items.splice(i, 0, queueElement);
                    isContinue = false;
                    break
                }
            }
            // 权重最低,则在队尾插入
            if(isContinue){
                this.items.push(queueElement);
            }
        }
    };
    
    // 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
    }

    // 6 toString方法
    PriorityQueue.prototype.toString = function () {  
        let resultString = '';
        for (let index = 0; index < this.items.length; index++) {
            resultString += this.items[i] + ' ';            
        }
        return resultString
    }
}

// 测试用例
var pq = new PriorityQueue();

// enqueue方法
pq.enqueue('abc', 100)
pq.enqueue('efg', 50)
pq.enqueue('hij', 300)

console.log(pq);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值