js数据结构与算法-双端队列的实现

双端队列:队列的两端都可以增加和删除。可先进先出,或后进先出。比如火车站验票,可正常排队,但如果比较紧急时可以跑到最前面去。

/**
   * 双端队列
   */
class Deque {
  #count = 0;//队列最大数量
  #lowestCount = 0;//目前第一个元素的下标
  #items = {};//队列
  //向前添加元素
  addFront(element) {
    if (this.isEmpty()) {
      //为空时 直接向后添加元素
      this.addBack(element);
    } else if (this.#lowestCount > 0) {
      //前面有元素被移除过 键-1处 添加元素
      this.#lowestCount--;
      this.#items[this.#lowestCount] = element;
    } else {
      //前面没有元素被移除过 所有元素从后往前都后移动一位 键0处 添加元素
      for (let i = this.#count; i > 0; i--) {
        this.#items[i] = this.#items[i - 1];
      }
      this.#count++;
      this.#lowestCount = 0;
      this.#items[0] = element;
    }
  }
  //向后添加元素
  addBack(element) {
    this.#items[this.#count] = element;
    this.#count++;
  }
  //从前移除元素
  removeFront() {
    if (this.isEmpty()) {
      return undefined;
    }
    const result = this.#items[this.#lowestCount];
    delete this.#items[this.#lowestCount];
    this.#lowestCount++;
    return result;
  }
  //从后移除元素
  removeBack() {
    if (this.isEmpty()) {
      return undefined;
    }
    const result = this.#items[this.#count - 1]
    delete this.#items[this.#count - 1]
    this.#count--;
    return result;
  }
  //返回前部第一个元素 第一个
  peekFront() {
    if (this.isEmpty()) {
      return null;
    }
    return this.#items[this.#lowestCount];
  };
  //返回后部第一个元素 最后一个
  peekBack() {
    if (this.isEmpty()) {
      return null;
    }
    return this.#items[this.#count - 1];
  };
  //队列是否为空
  isEmpty() {
    return this.size() === 0;
  }
  //队列中有几个元素
  size() {
    return this.#count - this.#lowestCount;
  }
  //toString
  toString() {
    if (this.isEmpty()) {
      return '';
    }
    let objString = `${this.#items[this.#lowestCount]}`;
    for (var i = this.#lowestCount + 1; i < this.#count; i++) {
      objString = `${objString},${this.#items[i]}`;
    }
    return objString;
  }
  //清空
  clear() {
    this.#items = {};
    this.#count = 0;
    this.#lowestCount = 0;
  }
}

const d1 = new Deque()
d1.addFront(1)//向前添加
d1.addFront(2)//向前添加
d1.addBack(3)//向后添加
d1.removeBack()//从后移除
d1.removeFront()//从前移除
d1.addFront(4)//向前添加
d1.addFront(5)//向前添加
d1.addBack(6)//向后添加
console.log(d1)

结果:

 

posted @ 2022-08-22 10:16  herry菌  阅读(47)  评论(0编辑  收藏  举报