javaScript实现一个队列的方法
编程学习 2021-07-04 14:06www.dzhlxh.cn编程入门
这篇文章主要介绍了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实现一个队列的方法的详细内容,更多关于javaScript实现一个队列的资料请关注狼蚁SEO其它相关文章!
编程语言
- ThinkPad 笔记本如何调节LCD屏幕亮度
- Dreamweaver制作网页打开特效教程
- Win10 Mobile 10586升级后无限重启怎么办 硬重启帮您
- Win8系统提示音频设备有问题有一个或多个音频服
- Xbox One版Win10首个预览版9月份发布
- 如何在textarea文本输入区内实现换行
- Win10 Build 9901系统更新 预览版新版本下载
- McAfee Framework存在远程格式串处理漏洞
- Win10家庭版今日(7月30)正式在中国官方商城开卖
- Win10 Mobile预览版更新完10536.1000后才收到10536.100
- Win10 RS2更新了什么-Win10 RS2最终版本号1704首曝
- Windows7如何查看回收站对应的文件夹有哪些方法
- Win10让Charms栏回归桌面的方法教程
- 取消Windows XP系统开机启动画面的小技巧
- win8系统怎么下载安装USB百兆网卡?
- XP系统下磁盘空间变少了怎么办?XP系统磁盘空间