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 @   樊顺  阅读(92)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示