1.隊列是遵循先進先出(FIFO)原則的一組有序的項,隊列在尾部添加元素,並從頂部移除元素,最新添加的元素必須排在隊列的末尾。生活中常見的例子如排隊等。 2.創建一個隊列類 class Queue{ constructor(){ this.count = 0;//記錄隊列的數量 this.lowes ...
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.運行結果