1.前言
2.yocto-queue了解
- 对大的数组上进行操作,考虑使用yocto-queue 来替代 Array,而不是采用 Array.push 和 Array.shift
- 队列是元素的有序列表,其中元素插入到队列的末尾并从队列的前面删除。队列基于先进先出 (FIFO) 原则工作
- 了解时间复杂度、空间复杂度
- 又熟悉了es6 class 私有属性、私有方法
- 熟悉Iterator Generator
3.源码
How it works:
`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.
*/
class Node {
value;
next;
constructor(value) {
this.value = value;
}
}
export default class Queue {
//es6 私有属性前边采用#表示,只能在内部使用
#head;
#tail;
#size;
constructor() {
//初始化清空当前当前属性 并让siez=0
this.clear();
}
enqueue(value) {
const node = new Node(value);
//进行判断是否第一次添加
if (this.#head) {
//这块看起来最开始不明白看了其他笔记 才有点理解为啥这么写了
this.#tail.next = node;
this.#tail = node;
} else {
this.#head = node;
this.#tail = node;
}
this.#size++;
}
//删除链表从头部开始删除
dequeue() {
const current = this.#head;
if (!current) {
return;
}
this.#head = this.#head.next;
this.#size--;
return current.value;
}
//清空整个链表
clear() {
this.#head = undefined;
this.#tail = undefined;
this.#size = 0;
}
//获取链表长度
get size() {
return this.#size;
}
* [Symbol.iterator]() {
let current = this.#head;
while (current) {
yield current.value;
current = current.next;
}
}
}