小编给大家分享一下如何用javaScript实现一个队列,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!
1.队列是遵循先进先出(FIFO)原则的一组有序的项,队列在尾部添加元素,并从顶部移除元素,最新添加的元素必须排在队列的末尾。生活中常见的例子如排队等。
2.创建一个队列类
class Queue{ constructor(){ this.count = 0;//记录队列的数量 this.lowestCount = 0;//记录当前队列头部的位置 this.items = [];//用来存储元素。 } }
3.添加元素
enqueue(element){ this.items[this.count] = element; this.count++; }
4.删除元素(只删除队列头部)
dequeue(){ if(this.isEmpty()){ return 'queue is null'; } let resulte = this.items[this.lowestCount]; delete this.items[this.lowestCount]; this.lowestCount++; return resulte; }
5.查看队列头部元素
peek(){ return this.items[this.lowestCount]; }
6.判断队列是否为空
isEmpty(){ return this.count - this.lowestCount === 0; }
7.清除队列的元素
clear(){ this.count = 0; this.lowestCount = 0; this.items = []; }
8.查看队列的长度
size(){ return this.count - this.lowestCount; }
9.查看队列的所有内容
toString(){ if(this.isEmpty())return "queue is null"; let objString = this.items[this.lowestCount]; for(let i = this.lowestCount+1; i < this.count;i++){ objString = `${objString},${this.items[i]}`; } return objString; }
10.完整代码
class Queue{ constructor(){ this.count = 0;//记录队列的数量 this.lowestCount = 0;//记录当前队列顶部的位置 this.items = [];//用来存储元素。 } enqueue(element){ this.items[this.count] = element; this.count++; } dequeue(){ if(this.isEmpty()){ return 'queue is null'; } let resulte = this.items[this.lowestCount]; delete this.items[this.lowestCount]; this.lowestCount++; return resulte; } peek(){ return this.items[this.lowestCount]; } isEmpty(){ return this.count - this.lowestCount === 0; } size(){ return this.count - this.lowestCount; } clear(){ this.count = 0; this.lowestCount = 0; this.items = []; } toString(){ if(this.isEmpty())return "queue is null"; let objString = this.items[this.lowestCount]; for(let i = this.lowestCount+1; i < this.count;i++){ objString = `${objString},${this.items[i]}`; } return objString; } }
11.运行结果
看完了这篇文章,相信你对如何用javaScript实现一个队列有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。