hello-algo/codes/javascript/chapter_stack_and_queue/array_queue.js

109 lines
2.6 KiB
JavaScript
Raw Normal View History

2022-12-13 00:00:06 +08:00
/**
* File: array_queue.js
* Created Time: 2022-12-13
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
*/
/* 基于环形数组实现的队列 */
class ArrayQueue {
2023-02-01 03:23:29 +08:00
#nums; // 用于存储队列元素的数组
#front = 0; // 队首指针,指向队首元素
#queSize = 0; // 队列长度
2022-12-13 00:00:06 +08:00
constructor(capacity) {
2023-02-01 03:23:29 +08:00
this.#nums = new Array(capacity);
2022-12-13 00:00:06 +08:00
}
/* 获取队列的容量 */
get capacity() {
2023-02-01 03:23:29 +08:00
return this.#nums.length;
2022-12-13 00:00:06 +08:00
}
/* 获取队列的长度 */
get size() {
2023-02-01 03:23:29 +08:00
return this.#queSize;
2022-12-13 00:00:06 +08:00
}
/* 判断队列是否为空 */
empty() {
2023-02-01 03:23:29 +08:00
return this.#queSize == 0;
2022-12-13 00:00:06 +08:00
}
/* 入队 */
push(num) {
if (this.size == this.capacity) {
console.log("队列已满");
return;
}
2023-02-01 03:23:29 +08:00
// 计算尾指针,指向队尾索引 + 1
// 通过取余操作,实现 rear 越过数组尾部后回到头部
const rear = (this.#front + this.size) % this.capacity;
// 将 num 添加至队尾
2023-02-01 03:23:29 +08:00
this.#nums[rear] = num;
this.#queSize++;
2022-12-13 00:00:06 +08:00
}
/* 出队 */
poll() {
const num = this.peek();
2023-02-01 03:23:29 +08:00
// 队首指针向后移动一位,若越过尾部则返回到数组头部
2022-12-14 00:02:25 +08:00
this.#front = (this.#front + 1) % this.capacity;
2023-02-01 03:23:29 +08:00
this.#queSize--;
2022-12-13 00:00:06 +08:00
return num;
}
/* 访问队首元素 */
peek() {
if (this.empty())
2022-12-20 21:02:09 +08:00
throw new Error("队列为空");
2023-02-01 03:23:29 +08:00
return this.#nums[this.#front];
2022-12-13 00:00:06 +08:00
}
/* 返回 Array */
toArray() {
// 仅转换有效长度范围内的列表元素
2023-02-01 03:23:29 +08:00
const arr = new Array(this.size);
for (let i = 0, j = this.#front; i < this.size; i++, j++) {
arr[i] = this.#nums[j % this.capacity];
2022-12-13 00:00:06 +08:00
}
return arr;
}
}
2022-12-20 21:02:09 +08:00
/* Driver Code */
2022-12-13 00:00:06 +08:00
/* 初始化队列 */
const capacity = 10;
const queue = new ArrayQueue(capacity);
/* 元素入队 */
queue.push(1);
queue.push(3);
queue.push(2);
queue.push(5);
queue.push(4);
2023-02-01 03:23:29 +08:00
console.log("队列 queue =", queue.toArray());
2022-12-13 00:00:06 +08:00
/* 访问队首元素 */
const peek = queue.peek();
console.log("队首元素 peek = " + peek);
/* 元素出队 */
const poll = queue.poll();
2023-02-01 03:23:29 +08:00
console.log("出队元素 poll = " + poll + ",出队后 queue =", queue.toArray());
2022-12-13 00:00:06 +08:00
/* 获取队列的长度 */
const size = queue.size;
console.log("队列长度 size = " + size);
/* 判断队列是否为空 */
const empty = queue.empty();
console.log("队列是否为空 = " + empty);
/* 测试环形数组 */
for (let i = 0; i < 10; i++) {
queue.push(i);
2022-12-13 00:00:06 +08:00
queue.poll();
2023-02-01 03:23:29 +08:00
console.log("第 " + i + " 轮入队 + 出队后 queue =", queue.toArray());
2022-12-13 00:00:06 +08:00
}