JavaScript系列-数据结构:队列

54 阅读1分钟

JavaScript系列-数据结构:队列

队列是一种先进先出的数据结构。

class Queue {
  constructor() {
    this.length = 0;
    this.queue = {};
  }
  // 从队列尾部进入
  push(node) {
    this.queue[this.length] = node;
    this.length++;
    return this.queue;
  }
  // 从队列头部出队
  shift() {
    const fq = this.queue[0];
    for (let i = 0; i < this.length - 1; i++) {
      this.queue[i] = this.queue[i + 1];
    }
    delete this.queue[this.length - 1];
    this.length--;
    return fq;
  }
  // 特殊情况的插队处理
  insert(i, node) {
    this.length++;
    for (let k = this.length - 1; k > i; k--) {
      this.queue[k] = this.queue[k - 1];
    }
    this.queue[i] = node;
    return this.queue;
  }
  // 特殊情况的离队处理
  out(i) {
    const rq = this.queue[i];
    for (let k = i; k < this.length - 1; k++) {
      this.queue[k] = this.queue[k + 1];
    }
    delete this.queue[this.length - 1];
    this.length--;
    return rq;
  }
  clear() {
    this.length = 0;
    this.queue = {};
  }
}
​
const q = new Queue();
q.push(1);
q.push(2);
q.push(3);
console.log(q.queue);
q.out(1);
console.log(q.queue);
​

\