双端队列 double-end queue 是一种允许我们同时从前端和后端添加和移除的元素的特殊队列。
双端队列同时遵守了先进先出和后进先出原则,可以说它是把队列和栈相结合的一种数据结构。

双端队列的方法

  • addFront(element) 在前端添加新元素
  • addBlack(element) 在后端添加新元素
  • removeFront() 从前端移除第一个元素
  • removeBack() 从后端移除第一个元素
  • peekFront() 返回前端的第一个元素
  • peekBack() 返回后端的第一个元素
  • isEmpty() 是否空双端队列
  • clear() 清空双端队列
  • size() 返回元素个数

    实现

    1. class deque {
    2. constructor() {
    3. this.count = 0;
    4. this.lowestCount = 0;
    5. this.items = {};
    6. }
    7. addFront(element) {
    8. if (this.isEmpty()) {
    9. this.addBack(element);
    10. } else if (this.lowestCount > 0) {
    11. this.lowestCount--;
    12. this.items[this.lowestCount] = element;
    13. } else {
    14. for (let i = this.count; i > 0; i--) {
    15. this.items[i] = this.items[i - 1];
    16. }
    17. this.count++;
    18. this.lowestCount = 0;
    19. this.items[0] = element;
    20. }
    21. }
    22. addBack(element) {
    23. this.items[this.count] = element;
    24. this.count++;
    25. }
    26. removeFront() {
    27. if (this.isEmpty) {
    28. return undefined;
    29. }
    30. const result = this.items[this.lowestCount];
    31. delete this.items[this.lowestCount];
    32. this.lowestCount++;
    33. return result;
    34. }
    35. removeBack() {
    36. if (this.isEmpty) {
    37. return undefined;
    38. }
    39. this.count--;
    40. const result = this.items[this.count];
    41. delete this.items[this.count];
    42. return result;
    43. }
    44. peekFront() {
    45. if (this.isEmpty) {
    46. return undefined;
    47. }
    48. return this.items[this.lowestCount];
    49. }
    50. peekBack() {
    51. if (this.isEmpty) {
    52. return undefined;
    53. }
    54. return this.items[this.count - 1];
    55. }
    56. isEmpty() {
    57. return this.size() === 0;
    58. }
    59. size() {
    60. return this.count - this.lowestCount;
    61. }
    62. clear() {
    63. this.items = {};
    64. this.count = 0;
    65. this.lowestCount = 0;
    66. }
    67. toString() {
    68. if (this.isEmpty()) {
    69. return '';
    70. }
    71. let objString = `${this.items[this.lowestCount]}`;
    72. for (let i = this.lowestCount + 1; i < this.count; i++) {
    73. objString = `${objString},${this.items[i]}`;
    74. }
    75. return objString;
    76. }
    77. }