語雀入口
https://www.yuque.com/along-n3gko/ezt5z9
介紹
佇列是遵循FIFO(First In First Out,先進先出,也稱為先來先服務)原則的一組有序的項, 佇列在尾部添加新元素,并從頂部移除元素,最新添加的元素必須排在佇列的末尾,
在現實中,最常見的佇列就是排隊,當然不允許插隊的存在哦

分析
實作一個佇列,首先需要一個存盤佇列的資料結構,我們可以使用陣列,
1 function Queue() { 2 var items = []; 3 }
基本方法
- 向佇列添加方法,新項只能添加在末尾
- 從佇列移除元素,遵循先進先出原則,所以最先添加項也是被最先移除的,
- 查看佇列長度
- 檢查佇列是否為空,為慷訓回傳true,否則回傳false
- 查看佇列頭元素
- 查看佇列尾元素
- 清空佇列
- 列印佇列元素
代碼實作
1 function Queue() { 2 var items = []; 3 this.enqueue = function(data) { 4 items.push(data); 5 }; 6 this.dequeue = function() { 7 return items.shift(); 8 }; 9 this.size = function() { 10 return items.length; 11 }; 12 this.isEmpty = function() { 13 return items.length === 0; 14 }; 15 16 this.head = function() { 17 return items[0] || null; 18 }; 19 this.tail = function() { 20 let len = items.length; 21 if (len > 0) { 22 return items[len - 1]; 23 } 24 return null; 25 }; 26 this.clear = function() { 27 items = []; 28 return true; 29 }; 30 this.show = function() { 31 console.log(items.toString()); 32 }; 33 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/88356.html
標籤:JavaScript
上一篇:Mac Chrome瀏覽器跨域指令快速啟動應用創建,避免每次在終端輸入指令
下一篇:鏈表
