diff --git a/codes/javascript/chapter_stack_and_queue/array_queue.js b/codes/javascript/chapter_stack_and_queue/array_queue.js index 89234952..902c7407 100644 --- a/codes/javascript/chapter_stack_and_queue/array_queue.js +++ b/codes/javascript/chapter_stack_and_queue/array_queue.js @@ -7,10 +7,10 @@ /* 基于环形数组实现的队列 */ class ArrayQueue { - #queue; // 用于存储队列元素的数组 - #front = 0; // 头指针,指向队首 - #rear = 0; // 尾指针,指向队尾 + 1 - #CAPACITY = 1e5; + #queue; // 用于存储队列元素的数组 + #front = 0; // 头指针,指向队首 + #rear = 0; // 尾指针,指向队尾 + 1 + #CAPACITY = 1e3; // 默认初始容量 constructor(capacity) { this.#queue = new Array(capacity ?? this.CAPACITY); @@ -34,10 +34,8 @@ class ArrayQueue { /* 入队 */ offer(num) { - if (this.size == this.capacity) { - console.log("队列已满"); - return; - } + if (this.size == this.capacity) + throw new Error("队列已满"); // 尾结点后添加 num this.#queue[this.#rear] = num; // 尾指针向后移动一位,越过尾部后返回到数组头部 @@ -56,14 +54,14 @@ class ArrayQueue { peek() { // 删除头结点 if (this.empty()) - throw new Error("The queue is empty!"); + throw new Error("队列为空"); return this.#queue[this.#front]; } /* 访问指定索引元素 */ get(index) { if (index >= this.size) - throw new Error("Index out of bounds!"); + throw new Error("索引越界"); return this.#queue[(this.#front + index) % this.capacity]; } @@ -80,6 +78,8 @@ class ArrayQueue { } } + +/* Driver Code */ /* 初始化队列 */ const capacity = 10; const queue = new ArrayQueue(capacity); diff --git a/codes/javascript/chapter_stack_and_queue/linkedlist_queue.js b/codes/javascript/chapter_stack_and_queue/linkedlist_queue.js index a05b10b9..cf1f3b3d 100644 --- a/codes/javascript/chapter_stack_and_queue/linkedlist_queue.js +++ b/codes/javascript/chapter_stack_and_queue/linkedlist_queue.js @@ -47,7 +47,7 @@ class LinkedListQueue { poll() { const num = this.peek(); if (!this.#front) { - throw new Error("No element in queue!") + throw new Error("队列为空") } // 删除头结点 this.#front = this.#front.next; @@ -58,7 +58,7 @@ class LinkedListQueue { /* 访问队首元素 */ peek() { if (this.size === 0) - throw new Error("No element in queue!"); + throw new Error("队列为空"); return this.#front.val; } diff --git a/codes/javascript/chapter_stack_and_queue/queue.js b/codes/javascript/chapter_stack_and_queue/queue.js index 5d26727f..7d4aeeee 100644 --- a/codes/javascript/chapter_stack_and_queue/queue.js +++ b/codes/javascript/chapter_stack_and_queue/queue.js @@ -4,6 +4,8 @@ * Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com) */ + +/* Driver Code */ /* 初始化队列 */ // JavaScript 没有内置的队列,可以把 Array 当作队列来使用 // 注意:由于是数组,所以 shift() 的时间复杂度是 O(n) @@ -20,7 +22,7 @@ queue.push(4); const peek = queue[0]; /* 元素出队 */ -// O(n) +// shift() 方法的时间复杂度为 O(n) const poll = queue.shift(); /* 获取队列的长度 */