JavaScript封装优先级队列

这篇博客介绍了如何创建一个优先级队列,该队列根据优先级插入和删除元素。通过`enqueue`方法添加元素,根据优先级将其插入到正确的位置,`dequeue`方法删除并返回最高优先级的元素,`front`方法查看队首元素,`isEmpty`检查队列是否为空,`size`获取队列长度,`toString`用于显示队列内容。示例展示了如何使用这个优先级队列实例。
摘要由CSDN通过智能技术生成
// 优先级队列
		function PriortyQueue(){
			// element 数据项
			// priorty 优先级别
			function QueueElement(element,priorty){
				// 保存数据,及保存优先级
				this.element = element
				this.priorty = priorty
			}
			// 封装属性
			this.items = []
			PriortyQueue.prototype.enqueue = function (element,priorty) {
				// 创建一个QueueElement 对象
				let queueElement = new QueueElement(element,priorty)
					// 判断队列是否为空、
					if(this.items.length === 0) {
						this.items.push(queueElement)
					} else {
						let added = false
						for(let i = 0; i < this.items.length; i++){
							if(queueElement.priorty < this.items[i].priorty) {
								this.items.splice(i,0,queueElement)
								// 已经找到了,结束循环,就不再往下循环了
								added = true
								break
							}
						}
						if (!added) {
							this.items.push(queueElement)
						}
					}
			}
			// 队列删除元素 ,只能从前端删除
			PriortyQueue.prototype.dequeue = function(){
				return this.items.shift()
			}
			// 查看最前面的一个元素
			PriortyQueue.prototype.front = function(){
				return this.items[0]
			}
			// 查看队列是否为空
			PriortyQueue.prototype.isEmpty = function(){
				return this.items.length === 0
			}
			// 查看元素个数
			PriortyQueue.prototype.size = function(){
				return this.items.length
			}
			// toString方法
			PriortyQueue.prototype.toString = function(){
				let resultString = ''
				for(let i = 0; i < this.items.length; i++){
					resultString = this.items[i] + ''
				}
				return resultString
			}
		}
		let q = new PriortyQueue()
		// 传入数据和优先级别
		q.enqueue('a',11)
		q.enqueue('b',2)
		q.enqueue('c',50)
		console.log(q)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值