队列的概念

  • 队列是一种遵从先进先出原则的有序集合
  • 添加新元素的一端称为队尾,另一端称为队首

    队列的实现

  • enQueue() 入队方法

  • deQueue() 出队方法
  • top() 获取队首值
  • size() 获取队列长度
  • clear() 清空队列 ```javascript class Queue { constructor() { this.queue = [] this.count = 0 } // 入队方法 enQueue(item) { this.queue.push(item) this.count++ }

    // 出队方法 deQueue() { if (this.isEmpty()) {

    1. return

    } this.count— return this.queue.shift(); }

    // 是否为空 isEmpty() { return this.count === 0 }

    // 获取队首元素值 top() { return this.queue[0] }

    size() { return this.count }

    // 清空队列 clear() { this.queue = [] this.count = 0 } }

const m = new Queue();

  1. ```javascript
  2. class Queue {
  3. constructor() {
  4. this.queue = {}
  5. this.count = 0
  6. // 用于记录队首的键
  7. this.head = 0
  8. }
  9. // 入队方法
  10. enQueue(item) {
  11. this.queue[this.count++] = item
  12. }
  13. // 出队方法
  14. deQueue() {
  15. if (this.isEmpty()) {
  16. return
  17. }
  18. const topValue = this.queue[this.head];
  19. delete this.queue[this.head]
  20. this.head++
  21. this.count--
  22. return topValue
  23. }
  24. // 是否为空
  25. isEmpty() {
  26. return this.count === 0
  27. }
  28. // 获取队首元素值
  29. top() {
  30. return this.queue[this.head]
  31. }
  32. size() {
  33. return this.count
  34. }
  35. // 清空队列
  36. clear() {
  37. this.queue = {}
  38. this.count = 0
  39. this.head = 0
  40. }
  41. }
  42. const m = new Queue();

双端队列

双端队列 指的是允许同时从队尾与队首两端进行存取操作的队列,操作更加灵活
双端队列与 JavaScript 中的数组操作十分相似, 只是不允许在数组两端以外的位置进行存取操作

  • addFront/addBack
  • removeFront/removeBack
  • frontTop/backTop
    ```javascript class Queue { constructor() { this.queue = {} this.count = 0 // 用于记录队首的键 this.head = 0 } // 队首添加 addFront(item) { this.queue[—this.head] = item }

    // 队尾添加 addBack(item) { this.queue[this.count++] = item }

    // 队首删除 removeFront() { if(this.isEmpty()) {

    1. return

    } const headValue = this.queue[this.head] delete this.queue[this.head++] return headValue }

    // 队尾删除 removeBack() { if(this.isEmpty()) {

    1. return

    } const backValue = this.queue[this.count - 1] delete this.queue[—this.count] return backValue }

    // 获取队首值 frontTop() { if (this.isEmpty()) {

    1. return

    } return this.queue[this.head] }

    // 获取队尾值 backTop() { if(this.isEmpty()) {

    1. return

    } return this.queue[this.count -1] } // 是否为空 isEmpty() { return this.size() === 0 }

    size() { return this.count - this.head }

    // 清空队列 clear() { this.queue = {} this.count = 0 this.head = 0 } }

const m = new Queue(); ```

leecode

力扣