首页 / JAVASCRIPT / JS中优先级队列实现
JS中优先级队列实现
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了JS中优先级队列实现,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1567字,纯文字阅读大概需要3分钟。
内容图文
![JS中优先级队列实现](/upload/InfoBanner/zyjiaocheng/992/8a0f1343e3944359944bd4b21e0473df.jpg)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>优先级队列</title> </head> <body> <script> //封装优先级队列 function PriorityQueue(){ //在PriorityQueue里重新创建一个类,可以理解为内部类 function QueueElement(element,priority){ this.element=element; this.priority =priority; } //封装属性 this.items = []; //实现插入方法 PriorityQueue.prototype.enqueue = function(element,priority){ //1.创造QueueElement 对象 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) } } } //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 resultsString = '' for(var i =0; i<this.items.length;i++){ resultsString += this.items[i] +' ' } return resultsString } } var pq = new PriorityQueue() pq.enqueue('abc',120) pq.enqueue('abce',100) pq.enqueue('abce',10) console.log(pq); </script> </body> </html>
运行结果
PS:
内容总结
以上是互联网集市为您收集整理的JS中优先级队列实现全部内容,希望文章能够帮你解决JS中优先级队列实现所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。