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