在 JavaScript 中實現迴圈佇列環形緩衝區


迴圈佇列

迴圈佇列是一種線性資料結構,其操作基於 FIFO(先進先出)原則,最後一個位置連接回第一個位置形成一個環。它也被稱為“環形緩衝區”。

迴圈佇列的優點之一是可以利用佇列前面的空間。在普通佇列中,一旦佇列已滿,即使佇列前面有空間,也不能插入下一個元素。但使用迴圈佇列,我們可以使用該空間來儲存新值。

問題

我們需要設計在 JavaScript 中實現迴圈佇列,該佇列可以支援以下操作:

  • MyCircularQueue(k) - 建構函式,將佇列的大小設定為 k。

  • Front() - 獲取佇列中的第一個元素。如果佇列為空,則返回 -1。

  • Rear() - 獲取佇列中的最後一個元素。如果佇列為空,則返回 -1。

  • enQueue(value) - 將元素插入迴圈佇列。如果操作成功,則返回 true。

  • deQueue() - 從迴圈佇列中刪除元素。如果操作成功,則返回 true。

  • isEmpty() - 檢查迴圈佇列是否為空。

  • isFull() - 檢查迴圈佇列是否已滿。

示例

以下是程式碼:

 線上演示

const CircularQueue = function(k) {
   this.size = k
   this.queue = []
   this.start1 = 0
   this.end1 = 0
   this.start2 = 0
   this.end2 = 0
}
CircularQueue.prototype.enQueue = function(value) {
   if(this.isFull()) {
      return false
   }
   if(this.end2 <= this.size - 1) {
      this.queue[this.end2++] = value
   } else {
      this.queue[this.end1++] = value
   }
   return true
}
CircularQueue.prototype.deQueue = function() {
   if(this.isEmpty()) {
      return false
   }
   if(this.queue[this.start2] !== undefined) {
      this.queue[this.start2++] = undefined
   } else {
      this.queue[this.start1++] = undefined
   }
   return true
}
CircularQueue.prototype.Front = function() {
   if(this.isEmpty()) {
      return -1
   }
   return this.queue[this.start2] === undefined ? this.queue[this.start1] :    this.queue[this.start2]
}
CircularQueue.prototype.Rear = function() {
   if(this.isEmpty()) {
      return -1
   }
   return this.queue[this.end1 - 1] === undefined ? this.queue[this.end2 - 1] :    this.queue[this.end1 - 1]
}
CircularQueue.prototype.isEmpty = function() {
   if(this.end2 - this.start2 + this.end1 - this.start1 <= 0) {
      return true
   }
   return false
}
CircularQueue.prototype.isFull = function() {
   if(this.end2 - this.start2 + this.end1 - this.start1 >= this.size) {
      return true
   }
   return false
}
const queue = new CircularQueue(2);
console.log(queue.enQueue(1));
console.log(queue.enQueue(2));
console.log(queue.enQueue(3));
console.log(queue.Rear());
console.log(queue.isFull());
console.log(queue.deQueue());
console.log(queue.enQueue(3));
console.log(queue.Rear());

輸出

true
true
false
2
true
true
true
3

更新於:2021年4月24日

1K+ 次瀏覽

啟動你的 職業生涯

完成課程獲得認證

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