双端队列跟队列的区别就是:队列只有一头进一头出,而双端队列两头都可以进可以出。灵活性变高,同样的也相对复杂。

    1. class Deque {
    2. constructor() {
    3. this.count = 0;
    4. this.lowestCount = 0;
    5. this.items = {};
    6. }
    7. /**
    8. * 向队列前端添加元素
    9. * @param {*} element
    10. */
    11. addFront(element) {
    12. if (this.isEmpty()) {
    13. this.addBack(element);
    14. } else if (this.lowestCount > 0) {
    15. this.lowestCount--;
    16. this.items[this.lowestCount] = element;
    17. } else {
    18. for (let i = this.count; i > 0; i--) {
    19. this.items[i] = this.items[i - 1];
    20. }
    21. this.count++;
    22. this.items[0] = element;
    23. }
    24. }
    25. /**
    26. * 向队尾添加新的项
    27. * @param {*} element
    28. */
    29. addBack(element) {
    30. this.items[this.count] = element;
    31. this.count++;
    32. }
    33. /**
    34. * 移除队列第一项
    35. */
    36. removeFront() {
    37. if (this.isEmpty()) {
    38. return;
    39. }
    40. let element = this.items[this.lowestCount];
    41. delete this.items[this.lowestCount];
    42. this.lowestCount++;
    43. return element;
    44. }
    45. /**
    46. * 移除队列最后一项
    47. */
    48. removeBack() {
    49. if (this.isEmpty()) {
    50. return;
    51. }
    52. this.count--;
    53. let element = this.items[this.count];
    54. delete this.items[this.count];
    55. return element;
    56. }
    57. /**
    58. * 返回队列第一项
    59. */
    60. peekFront() {
    61. return this.isEmpty() ? null : this.items[this.lowestCount];
    62. }
    63. /**
    64. * 返回队列最后一项
    65. */
    66. peekBack() {
    67. return this.isEmpty() ? null : this.items[this.count];
    68. }
    69. isEmpty() {
    70. return this.size() === 0;
    71. }
    72. size() {
    73. return this.count - this.lowestCount;
    74. }
    75. clear() {
    76. this.count = 0;
    77. this.lowestCount = 0;
    78. this.items = {};
    79. }
    80. toString() {
    81. if (this.isEmpty()) {
    82. return '';
    83. }
    84. let str = this.items[this.lowestCount].toString();
    85. for (let i = this.lowestCount + 1; i < this.count; i++) {
    86. str += `,${this.items[i]}`;
    87. }
    88. return str;
    89. }
    90. }