1. /*
    2. 基于线性表的 - 队列
    3. 尾部插入和头部删除
    4. 先进先出
    5. */
    6. class ListQueue{
    7. constructor() {
    8. this.arr = new Array();
    9. this.length = 0;
    10. this.size = 10;
    11. this.realloc = () => {
    12. let new_arr;
    13. if(this.length === this.size) {
    14. // 满了 增加内存
    15. this.size = this.size*2;
    16. new_arr = new Array(this.size);
    17. } else if(this.size > 10 && this.length <= Math.floor(this.size /4)) {
    18. this.size = Math.floor(this.size /2);
    19. new_arr = new Array(this.size);
    20. }
    21. if(new_arr) {
    22. this.arr.forEach((v, i) => {
    23. new_arr[i] = v;
    24. });
    25. this.arr = [...new_arr];
    26. }
    27. }
    28. }
    29. // 入队
    30. enqueue(value){
    31. this.arr[this.length] = value;
    32. this.length++;
    33. this.realloc();
    34. }
    35. // 出队
    36. dequeue() {
    37. if(!this.length) return undefined;
    38. const value = this.arr[0];
    39. for(let i = 0; i < (this.arr.length -1); i++){
    40. this.arr[i] = this.arr[i+1];
    41. }
    42. this.length--;
    43. this.realloc();
    44. return value;
    45. }
    46. }
    47. const list = new ListQueue();
    48. list.enqueue(1);
    49. list.enqueue(2);
    50. list.enqueue(3);
    51. list.enqueue(4);
    52. list.enqueue(5);
    53. console.log(list.dequeue());
    54. console.log(list);