队列是遵循先进先出 FIFO 原则的一组有序的项。
队列尾部添加新元素,并从顶部移除元素。最新添加的元素必须在队列末尾。

队列的方法

  • enqueue(element) 向队列发问添加新的元素
  • dequeue() 移除队列第一项并返回被除的元素
  • peek() / front() 返回队列第一个元素
  • isEmpty() 是否为空队列
  • size() 返回队列元素个数

    实现

    1. class Queue {
    2. constructor() {
    3. this.count = 0;
    4. this.lowestCount = 0;
    5. this.items = {};
    6. }
    7. enqueue(element) {
    8. this.items[this.count] = element;
    9. this.count++;
    10. }
    11. dequeue() {
    12. if (this.isEmpty()) {
    13. return undefined;
    14. }
    15. const result = this.item[this.lowestCount];
    16. delete this.items[this.lowestCount];
    17. this.lowestCount++;
    18. return result;
    19. }
    20. peek() {
    21. if (this.isEmpty()) {
    22. return undefined;
    23. }
    24. return this.items[this.lowestCount];
    25. }
    26. isEmpty() {
    27. return this.size() === 0;
    28. }
    29. size() {
    30. return this.count - this.lowestCount;
    31. }
    32. clear() {
    33. this.items = {};
    34. this.count = 0;
    35. this.lowestCount = 0;
    36. }
    37. toString() {
    38. if (this.isEmpty()) {
    39. return '';
    40. }
    41. let objString = `${this.item[this.lowestCount]}`;
    42. for (let i = this.lowestCount + 1; i < this.count; i++) {
    43. objString = `${(objString, $this.items[i])}`;
    44. }
    45. return objString;
    46. }
    47. }
    1. const Queue = (function () {
    2. const _item = new WeakMap();
    3. return class Queue{
    4. constructor() {
    5. _item.set(this, []);
    6. }
    7. enqueue(element) {
    8. _item.get(this).push(element);
    9. }
    10. dequeue() {
    11. if (this.isEmpty()) {
    12. return undefined;
    13. }
    14. return _item.get(this).shift();
    15. }
    16. front() {
    17. return _item.get(this)[0];
    18. }
    19. peek() {
    20. if (this.isEmpty()) {
    21. return undefined;
    22. }
    23. return _item.get(this)[this.size() - 1];
    24. }
    25. isEmpty() {
    26. return this.size() === 0;
    27. }
    28. size() {
    29. return _item.get(this).length;
    30. }
    31. clear() {
    32. _item.get(this).length = 0;
    33. }
    34. toString() {
    35. if (this.isEmpty()) {
    36. return '';
    37. }
    38. return _item.get(this).toString();
    39. }
    40. };
    41. })();