SOURCE

/*
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;
	}
}

class Queue {
	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;
		}

		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;
		}
	}
}

const queue = new Queue();

queue.enqueue('��');
queue.enqueue('��');
queue.enqueue('��');

for (let i of queue) {
	console.log(i)
}



console 命令行工具 X clear

                    
>
console