Skip to content

Commit

Permalink
feat: add linkedlist_queue in js to doc
Browse files Browse the repository at this point in the history
  • Loading branch information
S-N-O-R-L-A-X committed Dec 20, 2022
1 parent 1f118c2 commit 6e71572
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions docs/chapter_stack_and_queue/queue.md
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,72 @@ comments: true
=== "JavaScript"

```js title="linkedlist_queue.js"
class LinkedListQueue {
#front;
#rear; // 头结点 #front ,尾结点 #rear
#queSize = 0;

constructor() {
this.#front = null;
this.#rear = null;
}

/* 获取队列的长度 */
get size() {
return this.#queSize;
}

/* 判断队列是否为空 */
isEmpty() {
return this.size === 0;
}

/* 入队 */
offer(num) {
// 尾结点后添加 num
const node = new ListNode(num);
// 如果队列为空,则令头、尾结点都指向该结点
if (!this.#front) {
this.#front = node;
this.#rear = node;
// 如果队列不为空,则将该结点添加到尾结点后
} else {
this.#rear.next = node;
this.#rear = node;
}
this.#queSize++;
}

/* 出队 */
poll() {
const num = this.peek();
if (!this.#front) {
throw new Error("No element in queue!")
}
// 删除头结点
this.#front = this.#front.next;
this.#queSize--;
return num;
}

/* 访问队首元素 */
peek() {
if (this.size === 0)
throw new Error("No element in queue!");
return this.#front.val;
}

/* 将链表转化为 Array 并返回 */
toArray() {
let node = this.#front;
const res = new Array(this.size);
for (let i = 0; i < res.length; i++) {
res[i] = node.val;
node = node.next;
}
return res;
}
}
```

=== "TypeScript"
Expand Down

0 comments on commit 6e71572

Please sign in to comment.