JS數據結構-循環隊列

代碼示例:

/**
 * 循環隊列
 * @description 使用數組作爲容器,headIdx和tailBackIdx分別指向隊首元素和隊尾後一元素的位置並保持自增(通過與k取模獲得實際位置)
 * @param {number} k - 隊列的長度
 */
const CircularQueue = function(k) {
  // 循環隊列的容量
  this.capacity = k;
  // 隊列頭部元素的索引
  this.headIdx = 0;
  // 隊列尾部元素後一位置的索引
  this.tailBackIdx = 0;
  // 隊列(數組模擬)
  this.Q = [];
};

/**
 * 新元素入列邏輯
 * @param {number} el - 新元素
 * @return {boolean}
 */
CircularQueue.prototype.enqueue = function(el) {
  if (this.isFull()) {
    return false;
  }
  this.Q[this.tailBackIdx % this.k] = el;
  this.tailBackIdx++;
  return true;
};

/**
 * 新元素出列邏輯
 * @return {boolean}
 */
CircularQueue.prototype.dequeue = function() {
  if (this.isEmpty()) {
    return false;
  }
  this.headIdx++;
  return true;
};

/**
 * 新元素入列邏輯
 * @description 當headIdx和tailBackIdx相等時,則隊列中無元素,隊列爲空。
 * @return {boolean}
 */
CircularQueue.prototype.isEmpty = function() {
  return this.headIdx === this.tailBackIdx;
};

/**
 * 新元素入列邏輯
 * @description 當兩個指針之間([headIdx, ..., tailBackIdx])的元素長度與隊列容量相等時,則隊列已滿。
 * @return {boolean}
 */
CircularQueue.prototype.isFull = function() {
  return this.tailBackIdx - this.headIdx === this.capacity;
};

/**
 * 獲取隊首元素
 * @description 若隊列爲空,則返回-1;否則,通過[headIdx % k]形式獲取。
 * @return {number}
 */
CircularQueue.prototype.getFront = function() {
  return this.isEmpty() ? -1 : this.Q[this.headIdx % this.k];
};

/**
 * 獲取隊尾元素
 * @description 若隊列爲空,則返回-1;反之,通過[(tailBackIdx - 1) % k]形式獲取。
 * @return {number} 
 */
CircularQueue.prototype.getRear = function() {
  return this.isEmpty() ? -1 : this.Q[(this.tailBackIdx - 1) % this.k];
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章