From a18ed3fd6d9a38f7484b4cccfacb2626e2759bde Mon Sep 17 00:00:00 2001 From: S-N-O-R-L-A-X Date: Tue, 13 Dec 2022 00:01:03 +0800 Subject: [PATCH] feat: complement array_queue doc in js --- docs/chapter_stack_and_queue/queue.md | 75 ++++++++++++++++++++++++++- 1 file changed, 74 insertions(+), 1 deletion(-) diff --git a/docs/chapter_stack_and_queue/queue.md b/docs/chapter_stack_and_queue/queue.md index b9611a3..6b949c4 100644 --- a/docs/chapter_stack_and_queue/queue.md +++ b/docs/chapter_stack_and_queue/queue.md @@ -718,13 +718,86 @@ comments: true === "JavaScript" ```js title="array_queue.js" + /* 基于环形数组实现的队列 */ + class ArrayQueue { + queue; // 用于存储队列元素的数组 + front = 0; // 头指针,指向队首 + rear = 0; // 尾指针,指向队尾 + 1 + CAPACITY = 1e5; + constructor(capacity) { + this.queue = new Array(capacity ?? this.CAPACITY); + } + + /* 获取队列的容量 */ + get capacity() { + return this.queue.length; + } + + /* 获取队列的长度 */ + get size() { + // 由于将数组看作为环形,可能 rear < front ,因此需要取余数 + return (this.capacity + this.rear - this.front) % this.capacity; + } + + /* 判断队列是否为空 */ + empty() { + return this.rear - this.front == 0; + } + + /* 入队 */ + offer(num) { + if (this.size == this.capacity) { + console.log("队列已满"); + return; + } + // 尾结点后添加 num + this.queue[this.rear] = num; + // 尾指针向后移动一位,越过尾部后返回到数组头部 + this.rear = (this.rear + 1) % this.capacity; + } + + /* 出队 */ + poll() { + const num = this.peek(); + // 队头指针向后移动一位,若越过尾部则返回到数组头部 + this.front = (this.front + 1) % this.capacity; + return num; + } + + /* 访问队首元素 */ + peek() { + // 删除头结点 + if (this.empty()) + throw new Error("The queue is empty!"); + return this.queue[this.front]; + } + + /* 访问指定索引元素 */ + get(index) { + if (index >= this.size) + throw new Error("Index out of bounds!"); + return this.queue[(this.front + index) % this.capacity]; + } + + /* 返回 Array */ + toArray() { + const siz = this.size; + const cap = this.capacity; + // 仅转换有效长度范围内的列表元素 + const arr = new Array(siz); + for (let i = 0, j = this.front; i < siz; i++, j++) { + arr[i] = this.queue[j % cap]; + } + return arr; + } + } ``` === "TypeScript" ```typescript title="array_queue.ts" - + /* 基于环形数组实现的队列 */ class ArrayQueue { private queue: number[]; // 用于存储队列元素的数组