javaScript實(shí)現(xiàn)一個(gè)隊(duì)列的方法
1.隊(duì)列是遵循先進(jìn)先出(FIFO)原則的一組有序的項(xiàng),隊(duì)列在尾部添加元素,并從頂部移除元素,最新添加的元素必須排在隊(duì)列的末尾。生活中常見(jiàn)的例子如排隊(duì)等。
2.創(chuàng)建一個(gè)隊(duì)列類
class Queue{ constructor(){ this.count = 0;//記錄隊(duì)列的數(shù)量 this.lowestCount = 0;//記錄當(dāng)前隊(duì)列頭部的位置 this.items = [];//用來(lái)存儲(chǔ)元素。 }}
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ì)列的長(zhǎng)度
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 = [];//用來(lái)存儲(chǔ)元素。 } 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)一個(gè)隊(duì)列的方法的詳細(xì)內(nèi)容,更多關(guān)于javaScript實(shí)現(xiàn)一個(gè)隊(duì)列的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Python獲取抖音關(guān)注列表封號(hào)賬號(hào)的實(shí)現(xiàn)代碼2. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報(bào)錯(cuò)問(wèn)題分析3. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究4. 解決Python 進(jìn)程池Pool中一些坑5. php測(cè)試程序運(yùn)行速度和頁(yè)面執(zhí)行速度的代碼6. Python如何讀寫(xiě)CSV文件7. 三個(gè)不常見(jiàn)的 HTML5 實(shí)用新特性簡(jiǎn)介8. ajax請(qǐng)求添加自定義header參數(shù)代碼9. python利用os模塊編寫(xiě)文件復(fù)制功能——copy()函數(shù)用法10. 無(wú)線標(biāo)記語(yǔ)言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁(yè)
