javaScript實(shí)現(xiàn)一個隊(duì)列的方法
1.隊(duì)列是遵循先進(jìn)先出(FIFO)原則的一組有序的項(xiàng),隊(duì)列在尾部添加元素,并從頂部移除元素,最新添加的元素必須排在隊(duì)列的末尾。生活中常見的例子如排隊(duì)等。
2.創(chuàng)建一個隊(duì)列類
class Queue{ constructor(){ this.count = 0;//記錄隊(duì)列的數(shù)量 this.lowestCount = 0;//記錄當(dāng)前隊(duì)列頭部的位置 this.items = [];//用來存儲元素。 }}
3.添加元素
enqueue(element){ this.items[this.count] = element; this.count++; }
4.刪除元素(只刪除隊(duì)列頭部)
dequeue(){ if(this.isEmpty()){ return ’queue is null’; } let resulte = this.items[this.lowestCount]; delete this.items[this.lowestCount]; this.lowestCount++; return resulte; }
5.查看隊(duì)列頭部元素
peek(){ return this.items[this.lowestCount]; }
6.判斷隊(duì)列是否為空
isEmpty(){ return this.count - this.lowestCount === 0; }
7.清除隊(duì)列的元素
clear(){ this.count = 0; this.lowestCount = 0; this.items = []; }
8.查看隊(duì)列的長度
size(){ return this.count - this.lowestCount; }
9.查看隊(duì)列的所有內(nèi)容
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;//記錄隊(duì)列的數(shù)量 this.lowestCount = 0;//記錄當(dāng)前隊(duì)列頂部的位置 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.運(yùn)行結(jié)果

以上就是javaScript實(shí)現(xiàn)一個隊(duì)列的方法的詳細(xì)內(nèi)容,更多關(guān)于javaScript實(shí)現(xiàn)一個隊(duì)列的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. ASP新手必備的基礎(chǔ)知識2. asp文件用什么軟件編輯3. CentOS郵箱服務(wù)器搭建系列——SMTP服務(wù)器的構(gòu)建( Postfix )4. js實(shí)現(xiàn)計(jì)算器功能5. golang中json小談之字符串轉(zhuǎn)浮點(diǎn)數(shù)的操作6. 通過IEAD+Maven快速搭建SSM項(xiàng)目的過程(Spring + Spring MVC + Mybatis)7. 利用CSS制作3D動畫8. IDEA 2020.1.2 安裝教程附破解教程詳解9. Vue axios獲取token臨時令牌封裝案例10. JS中6個對象數(shù)組去重的方法

網(wǎng)公網(wǎng)安備