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];
};

 

posted @ 2022-09-09 19:06  樊顺  阅读(84)  评论(0编辑  收藏  举报