在 JavaScript 中建立佇列


儘管 JavaScript 中的陣列提供了佇列的所有功能,但我們還是實現了自己的佇列類。我們的類將具有以下功能 −

  •  enqueue(element):新增到佇列中的函式元素。
  •  dequeue():從佇列中刪除元素的函式。
  •  peek():從佇列的前面返回元素。
  •  isFull():檢查是否已達到佇列上的元素限制。
  •  isEmpty():檢查佇列是否為空。
  •  clear():刪除所有元素。
  •  display():顯示陣列的所有內容

讓我們首先定義一個簡單的類,其建構函式採用佇列的最大大小,並在我們為該類實現其他函式時為我們提供幫助的幫助程式函式。在我們實現了堆疊時,我們還將使用陣列實現佇列。

示例

class Queue {
   constructor(maxSize) {
      // Set default max size if not provided
      if (isNaN(maxSize)) {
         maxSize = 10;
       }
      this.maxSize = maxSize;
      // Init an array that'll contain the queue values.
      this.container = [];
   }
   // Helper function to display all values while developing
   display() {
      console.log(this.container);
   }
   // Checks if queue is empty
   isEmpty(){
      return this.container.length === 0;
   }
   // checks if queue is full
   isFull() {
      return this.container.length >= this.maxSize;
   }
}

我們還定義了另外兩個函式,isFull 和 isEmpty 以檢查佇列是否已滿或為空。

isFull 函式只檢查容器的長度是否等於或大於 maxSize,並相應返回。

isEmpty 函式檢查容器的大小是否為 0。

在我們定義其他操作時,這將很有用。我們從現在開始定義的函式都將進入 Queue 類。

更新於:15-6 月-2020

622 次瀏覽

啟動你的職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.