隊列,又稱爲佇列(queue),是先進先出(FIFO, First-In-First-Out)的線性表。 在具體應用中一般用鏈表或者數組來實現。 隊列只容許在後端(稱爲rear)進行插入操做, 在前端(稱爲front)進行刪除操做。 隊列的操做方式和堆棧相似, 惟一的區別在於隊列只容許新數據在後端進行添加。
以上是 維基百科 關於隊列的描述,轉換爲人話就是大概這麼幾條:前端
先入先出
的數據結構兩個指針進行操做數據後端
入隊
指針出隊
指針兩個異常數組
Queue Overflow
隊列溢出數據結構
Queue Underflow
隊列下溢測試
知道了 棧
的數據結構後(若是不知道請翻閱上篇),隊列
理解起來就特別簡單了。首先 棧
是 先入後出
,相似於 羽毛球桶
。而 隊列
是 先入先出
,相似於現實中的 排隊
,先到的先排,後到的後排。this
和棧差很少, 隊列也有兩個操做: 入隊enqueue
和出隊dequeue
。只不過隊列是經過兩個指針
來控制隊列的入隊和出隊
。spa
class Queue { constructor(max = 10000) { this.max = max; // 隊列最大值 this.data = new Array(max); // 初始化空隊列 this.p = 0; // 入隊指針 this.q = 0; // 出隊指針 this.size = 0; // 初始化隊列大小 } // 入隊 enqueue(item) { if (this.size >= this.max) { throw new Error("Queue Overflow"); // 隊列溢出 } this.data[this.p++] = item; // 入隊指針指向下一個地址 this.size++; // 隊列大小 +1 if (this.p >= this.max) { // 入隊指針到頭 從新回到隊列初始位置 造成一個閉環 this.p = 0; } } // 出隊 dequeue() { if (this.size === 0) { throw new Error("Queue Underflow"); // 隊列下溢 } let target = this.data[this.q++]; this.size--; if (this.q >= this.max) { // 出隊指針到頭 從新回到隊列的初始位置 造成一個閉環 this.q = 0; } return target; } }
let p = new Queue(); p.enqueue(1); p.enqueue(2); p.enqueue(3); p.enqueue(4); p.enqueue(5); p.enqueue(6); console.log(p.dequeue(), p); /* 1 Queue { max: 10000, data: [ 1, 2, 3, 4, 5, 6, <9994 empty items> ], p: 6, q: 1, size: 5 } */
能夠看到,new
了一個隊列p
。又依次向隊列p
中放了6個元素
。最後又取出了隊列
中的一個元素,取出的元素
便是第一次
放進隊列中的元素 1
。最後打印結果便是 1
,和隊列p
,其中入隊指針
指向了6
,出隊指針
指向了1
。指針