• 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];
    };
  • 相关阅读:
    【HNOI 2002】 营业额统计
    【BZOJ 3224】 普通平衡树
    【NOIP2014】 联合权值
    【NOIP2016】 组合数问题
    BZOJ2212 POI2011Tree Rotations(线段树合并)
    LOJ114 k大(xiao)异或和(线性基)
    LOJ121 动态图连通性(LCT)
    BZOJ3569 DZY Loves Chinese II(随机化+树上差分+线性基)
    BZOJ3237 AHOI2013连通图(线段树分治+并查集)
    BZOJ2208 JSOI2010连通数(floyd+bitset)
  • 原文地址:https://www.cnblogs.com/fanqshun/p/16673777.html
Copyright © 2020-2023  润新知