数据结构——单向链表

构建链表

  1. class Node {
  2. constructor(el) {
  3. this.el = el; // 节点元素
  4. this.next = null; // 下一个节点
  5. }
  6. }
  7. class LinkList {
  8. constructor() {
  9. this.le = 0;
  10. this.head = new Node("head"); // 头节点
  11. }
  12. get length() {
  13. return this.le;
  14. }
  15. /**
  16. *
  17. * @param {any} el 查找的节点
  18. * @description 查找某个节点
  19. * @returns 返回找到的节点或者null
  20. */
  21. find(el) {
  22. let currNode = this.head; //当前节点
  23. while (currNode.el !== el) {
  24. if (currNode.next === null) {
  25. break;
  26. }
  27. currNode = currNode.next;
  28. }
  29. return currNode;
  30. }
  31. /**
  32. * @param {any} newEl 新节点
  33. * @param {any} el 链表的节点
  34. * @description 向链表的某个指定节点后面插入新的节点, 如果指定节点为空,则在链表末尾加
  35. */
  36. insert(newEl, el) {
  37. let newNode = new Node(newEl);
  38. let currNode = this.find(el);
  39. currNode.next = newNode;
  40. this.le++;
  41. return this;
  42. }
  43. /**
  44. *
  45. * @param {any} el 查找的节点
  46. * @description 查找某个节点前面的节点
  47. * @returns 返回找到的节点或者null
  48. */
  49. findPrevious(el) {
  50. let currNode = this.head;
  51. const exist = this.find(el).el === el;
  52. if (!exist) {
  53. console.log(`can not find ${el}`);
  54. return;
  55. }
  56. while (currNode.next !== null && currNode.next.el !== el) {
  57. currNode = currNode.next;
  58. }
  59. return currNode;
  60. }
  61. /**
  62. *
  63. * @param {any} el 被删的节点
  64. * @description 删除某个节点
  65. */
  66. remove(el) {
  67. let preNode = this.findPrevious(el);
  68. if (preNode) {
  69. preNode.next = preNode.next.next;
  70. this.le--;
  71. return this;
  72. } else {
  73. console.log(`can not find ${el}`);
  74. return;
  75. }
  76. }
  77. /**
  78. * @description 打印链表
  79. */
  80. print() {
  81. let currNode = this.head;
  82. const nodeArr = [];
  83. if (!this.le) {
  84. console.log(`list is empty`);
  85. return;
  86. }
  87. do {
  88. nodeArr.push(currNode.next.el);
  89. currNode = currNode.next;
  90. } while (currNode.next !== null);
  91. console.log(nodeArr.join(` -> `));
  92. }
  93. }