# queue-队列

// 队列: 先入先出
class Queue {
  constructor() {
    this.items = {};
    this.length = 0;
    this.peekKey = 0; //记录当前顶部元素的key
  }

  //入队
  enqueue(node) {
    this.items[this.length] = node;
    this.length++;
  }

  //出队
  dequeue() {
    if (this.isEmpty()) {
      return null;
    }
    const node = this.items[this.peekKey];
    delete this.items[this.peekKey];
    this.length--;
    this.peekKey++;
    return node;
  }

  isEmpty() {
    return this.length === 0;
  }

  //获取队头元素
  front() {
    if (this.isEmpty()) {
      return null;
    }
    return this.items[this.peekKey];
  }

  clear() {
    this.items = {};
    this.length = 0;
    this.peekKey = 0;
  }

  size() {
    return this.length;
  }
}

const s = new Queue();
s.enqueue("node-1");
s.enqueue("node-2");

console.log(s.dequeue()); //node-1
console.log(s.dequeue()); //node-2
Last Updated: 4/17/2022, 7:45:45 PM