队列是遵循先进先出 FIFO 原则的一组有序的项。
队列尾部添加新元素,并从顶部移除元素。最新添加的元素必须在队列末尾。
队列的方法
- enqueue(element) 向队列发问添加新的元素
- dequeue() 移除队列第一项并返回被除的元素
- peek() / front() 返回队列第一个元素
- isEmpty() 是否为空队列
-
实现
class Queue {constructor() {this.count = 0;this.lowestCount = 0;this.items = {};}enqueue(element) {this.items[this.count] = element;this.count++;}dequeue() {if (this.isEmpty()) {return undefined;}const result = this.item[this.lowestCount];delete this.items[this.lowestCount];this.lowestCount++;return result;}peek() {if (this.isEmpty()) {return undefined;}return this.items[this.lowestCount];}isEmpty() {return this.size() === 0;}size() {return this.count - this.lowestCount;}clear() {this.items = {};this.count = 0;this.lowestCount = 0;}toString() {if (this.isEmpty()) {return '';}let objString = `${this.item[this.lowestCount]}`;for (let i = this.lowestCount + 1; i < this.count; i++) {objString = `${(objString, $this.items[i])}`;}return objString;}}
const Queue = (function () {const _item = new WeakMap();return class Queue{constructor() {_item.set(this, []);}enqueue(element) {_item.get(this).push(element);}dequeue() {if (this.isEmpty()) {return undefined;}return _item.get(this).shift();}front() {return _item.get(this)[0];}peek() {if (this.isEmpty()) {return undefined;}return _item.get(this)[this.size() - 1];}isEmpty() {return this.size() === 0;}size() {return _item.get(this).length;}clear() {_item.get(this).length = 0;}toString() {if (this.isEmpty()) {return '';}return _item.get(this).toString();}};})();
