概念

链表存储有序的元素集合,但不同于数组,链表中的元素在内存中并不是连续放置的。每个元素由一个存储元素本身的节点和一个指向下一个元素的引用(也称指针或链接)组成。
优点:添加或移除元素的时候不需要移动其他元素
缺点:想要查找元素时,要从表头开始进行迭代查找

单链表

  1. function LinkedList() {
  2. function Node(element) {
  3. this.element = element;
  4. this.next = null;
  5. }
  6. let length = 0;
  7. let head = null;
  8. // 添加元素
  9. this.append = function (element) {
  10. let node = new Node(element);
  11. let current;
  12. if (head === null) {
  13. head = node;
  14. } else {
  15. current = head;
  16. while (current.next) {
  17. current = current.next;
  18. }
  19. current.next = node;
  20. }
  21. length++;
  22. };
  23. // 移除特定位置的元素
  24. this.removeAt = function (position) {
  25. if (position > -1 && position < length) {
  26. let current = head;
  27. let previous, index = 0;
  28. if (position === 0) {
  29. head = current.next;
  30. } else {
  31. // 找到指定位置的元素
  32. while (index++ < position) {
  33. previous = current;
  34. current = current.next;
  35. }
  36. previous.next = current.next;
  37. }
  38. length--;
  39. return current.element;
  40. } else {
  41. return null;
  42. }
  43. };
  44. // 在指定位置插入元素
  45. this.insert = function (position, element) {
  46. if (position >= 0 && position <= length) {
  47. let node = new Node(element);
  48. let current = head;
  49. let previous, index = 0;
  50. if (position === 0) {
  51. node.next = current;
  52. head = node;
  53. } else {
  54. // 找到指定位置的元素
  55. while (index++ < position) {
  56. previous = current;
  57. current = current.next;
  58. }
  59. node.next = current;
  60. previous.next = node;
  61. }
  62. length++;
  63. return true;
  64. } else {
  65. return false;
  66. }
  67. };
  68. // 将 LinkedList 对象转换为字符串
  69. this.toString = function () {
  70. let current = head;
  71. let string = '';
  72. while (current) {
  73. string += current.element + '';
  74. current = current.next;
  75. }
  76. return string;
  77. };
  78. // 返回指定元素的索引
  79. this.indexOf = function (element) {
  80. let current = head;
  81. let index = 0;
  82. while (current) {
  83. if (current.element === element) {
  84. return index;
  85. }
  86. index++;
  87. current = current.next;
  88. }
  89. return -1;
  90. };
  91. // 移除指定元素
  92. this.remove = function (element) {
  93. let index = this.indexOf(element);
  94. return this.removeAt(index);
  95. };
  96. // 链表是否为空
  97. this.isEmpty = function () {
  98. return length === 0;
  99. };
  100. // 链表大小
  101. this.size = function () {
  102. return length;
  103. };
  104. // 返回链表头
  105. this.getHead = function () {
  106. return head;
  107. };
  108. }