数据结构——单向链表

构建链表

class Node {
  constructor(el) {
    this.el = el; // 节点元素
    this.next = null; // 下一个节点
  }
}

class LinkList {
  constructor() {
    this.le = 0;
    this.head = new Node("head"); // 头节点
  }

  get length() {
    return this.le;
  }

  /**
   *
   * @param {any} el 查找的节点
   * @description 查找某个节点
   * @returns 返回找到的节点或者null
   */
  find(el) {
    let currNode = this.head; //当前节点
    while (currNode.el !== el) {
      if (currNode.next === null) {
        break;
      }
      currNode = currNode.next;
    }
    return currNode;
  }

  /**
   * @param {any} newEl 新节点
   * @param {any} el 链表的节点
   * @description 向链表的某个指定节点后面插入新的节点, 如果指定节点为空,则在链表末尾加
   */
  insert(newEl, el) {
    let newNode = new Node(newEl);
    let currNode = this.find(el);
    currNode.next = newNode;
    this.le++;
    return this;
  }

  /**
   *
   * @param {any} el 查找的节点
   * @description 查找某个节点前面的节点
   * @returns 返回找到的节点或者null
   */
  findPrevious(el) {
    let currNode = this.head;
    const exist = this.find(el).el === el;
    if (!exist) {
      console.log(`can not find ${el}`);
      return;
    }
    while (currNode.next !== null && currNode.next.el !== el) {
      currNode = currNode.next;
    }
    return currNode;
  }

  /**
   *
   * @param {any} el 被删的节点
   * @description 删除某个节点
   */
  remove(el) {
    let preNode = this.findPrevious(el);
    if (preNode) {
      preNode.next = preNode.next.next;
      this.le--;
      return this;
    } else {
      console.log(`can not find ${el}`);
      return;
    }
  }

  /**
   * @description 打印链表
   */
  print() {
    let currNode = this.head;
    const nodeArr = [];
    if (!this.le) {
      console.log(`list is empty`);
      return;
    }
    do {
      nodeArr.push(currNode.next.el);
      currNode = currNode.next;
    } while (currNode.next !== null);

    console.log(nodeArr.join(` -> `));
  }
}