1. /*
    2. 基于链表的 - 队列
    3. 尾部插入和头部删除
    4. 先进先出
    5. */
    6. class LinkListQueue{
    7. constructor() {
    8. this.length = 0;
    9. this.head = null;
    10. this.tail = null;
    11. }
    12. // 入队
    13. enqueue(value){
    14. if(!this.tail) {
    15. this.head = this.tail = {value, next: null, prev: null};
    16. } else {
    17. this.tail.next = {value, next: null, prev: this.tail};
    18. this.tail = this.tail.next
    19. }
    20. this.length++;
    21. }
    22. // 出队
    23. dequeue() {
    24. let value;
    25. if(!this.head) return undefined;
    26. else{
    27. const value = this.head.value;
    28. if(!this.head.next){
    29. // 只剩最后一个了
    30. this.head = this.tail = null;
    31. } else {
    32. this.head.next.prev = null;
    33. this.head = this.head.next;
    34. }
    35. this.length--;
    36. return value;
    37. }
    38. }
    39. }
    40. const list = new LinkListQueue();
    41. list.enqueue(1);
    42. list.enqueue(2);
    43. list.enqueue(3);
    44. list.enqueue(4);
    45. console.log(list.dequeue());
    46. console.log(list);

    算法总结:
    image.png