链表

78 阅读1分钟

链表结构很多,最常见三种最常见的链表结构,它们分别是:单链表、双向链表和循环链表。 单链表

单链表.webp

双向链表

双向链表.webp

循环链表

循环链表.webp

常见链表操作

class Node{
  constructor(element){
    this.next = null;
    this.element = element;
  }
}

class LinkedList {
  constructor(){
    this.head = new Node('head');
  }

  findByValue(item) {
    let currentNode = this.head;
    while (currentNode !== null && currentNode.element !== item) {
      currentNode = currentNode.next
    }
    return currentNode === null ? -1 : currentNode
  }

  findByIndex(index) {
    let currentNode = this.head;
    let pos = 0;
    while (currentNode !== null && pos !== index) {
      currentNode = currentNode.next;
      pos++
    }
    return currentNode === null ? -1 : currentNode
  }
  insert(newElement, element) {
    let elementNode = this.findByValue(element);
    if (elementNode === -1){
      return;
    }
    let newElementNode = new Node(newElement);
    let p = elementNode.next;
    element.next = newElementNode;
    newElementNode.next = p
  }

  findPrev(item) {
    let head = this.head;
    while (head.next !== null){
      if (head.next.element === item){
        return head;
      }
      head = head.next;
    }
    return -1;
  }

  remove(item) {
    let findNode = this.findPrev(item);
    if (findNode !== -1){
      let p = item.next;
      findNode.next = p;
    }
  }

  //反转单链表
  reverseList() {
    let head = this.head;
    let p = head.next;
    while(p !== null){
      let next = p.next;
      let m = head.next;
      head.next = p;
      p.next = m;
      p = next;
    }
    head.next = p;
  }

  checkCircle() {
    let fast = this.head.next;
    let slow = this.head;
    while (fast !== null && fast.next !== null) {
      fast = fast.next.next;
      slow = slow.next;
      if (slow === fast) return true
    }
    return false
  }
  mergeSortedLists(listA, listB){
    let newListHead = undefined;
    if (!listA){
      return listB;
    }
    if (!listB){
      return listA;
    }

    if (listA.element < listB.element){
      newListHead = listA;
      listA = listA.next;
    } else {
      newListHead = listB;
      listB = listB.next;
    }
    while(listA !== null && listB !== null){
      if (listA.element > listB.element){
        newListHead.next = listB;
        listB = listB.next;
      } else {
        newListHead.next = listA;
        listA = listA.next;
      }
    }
    if (listA !== null){
      newListHead.next = listA;
    }
    if (listB !== null){
      newListHead.next = listB;
    }
  }
}