数据结构—js队列结构封装

 1、队列的封装

function Queue() {
        this.items = []
        // 1.入队
        Queue.prototype.enqueue = function (element) {
            this.items.push(element)
        }
        // 2.出队
        Queue.prototype.dequeue = function () {
            this.items.shift()
        }
        // 3.查看前端元素
        Queue.prototype.front = function () {
            return this.items[0]
        }
        // 4.判断是否为空
        Queue.prototype.isEmpty = function () {
            return this.items.length === 0
        }
        // 5.获取元素个数
        Queue.prototype.size = function () {
            return this.items.length
        }
        // 6.toString方法
        Queue.prototype.toString = function () {
            let resultString = ''
            for(let i = 0; i < this.items.length; i++){
                resultString += this.items[i]
            }
            return resultString
        }
    }

2、优先级队列封装

内部封装队列元素类,包含元素和优先级属性,在入队操作时遍历判断元素优先级所处位置进行插入,其他操作和普通队列一致。

function PriorityQueue() {
        this.items = []
        function QueueElement(element, priority) {
            this.element = element
            this.priority = priority
        }

        PriorityQueue.prototype.enqueue = function (element, priority) {
            let queueElement = new QueueElement(element, priority)
            if(this.items.length === 0){
                this.items.push(queueElement)
            }else {
                let flag = false
                for (let i = 0; i < this.items.length; i++){
                    if (priority < this.items[i].priority) {
                        this.items.splice(i, 0, queueElement)
                        flag = true
                        break
                    }
                }
                if (!flag){
                    this.items.push(queueElement)
                }
            }
        }
        // 2.出队
        PriorityQueue.prototype.dequeue = function () {
            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 i = 0; i < this.items.length; i++){
                resultString += this.items[i].element + '-' + this.items[i].priority + ' '
            }
            return resultString
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值