第三十二期 yocto-queue笔记

255 阅读1分钟
// 节点,作为链表的某一项
class Node {
    value;
    next;

    constructor(value) {
        this.value = value;
    }
}

// export default class Queue {
class Queue {
    // 之前这里疑惑是啥意思,后来发现其实就是等于construtor里面的this赋值,这里的意思就是这三个值默认为undefined
    #head;
    #tail;
    #size;
    
    // 实例初始化
    constructor() {
        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;
        }
        // 入队成功后长度加1
        this.#size++;
    }
    // 出队
    dequeue() {
        const current = this.#head;
        if (!current) {
            return;
        }
        // 将头部指针向后移一个,并且长度减1,并会烦出队的元素
        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;
        console.log('current: ', current);
        // 判断头部指针是否还存在
        while (current) {
            // yield后面的值是当前迭代返回的值
            yield current.value;
            // 头部指针向后移一位
            current = current.next;
        }
    }
}

总结:啥时候需要使用这个,有无具体使用场景。