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]; };
分类:
JavaScript
, 数据结构与算法
标签:
JavaScript
, 数据结构与算法
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?