单向链表

Published: · LastMod: April 07, 2024 · 429 words

链表 🔗

链表是一种物理储存上非联系,数据元素的逻辑顺序通过链表中的指针链接次序,实现的一种线性储存结构。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
class LinkNode {
  value: string;
  next: LinkNode;
  constructor(value: string) {
    this.value = value;
  }
}

class LinkedList {
  head: LinkNode;
  tail: LinkNode;
  constructor() {}

  prepend(value: string) {
    const node = new LinkNode(value);
    node.next = this.head;
    this.head = node;

    if (!this.tail) {
      this.tail = node;
    }

    return this;
  }

  append(value: string) {
    const node = new LinkNode(value);

    if (!this.head && !this.tail) {
      this.head = node;
      this.tail = node;
      return this;
    }

    this.tail.next = node;
    this.tail = node;
    return this;
  }

  insert(value: string, index: number) {
    if (index === 0) {
      return this.prepend(value);
    } else {
      let count = 1;
      let current = this.head;
      const node = new LinkNode(value);

      while (current) {
        if (count === index) break;
        current = current.next;
        count++;
      }

      if (current) {
        node.next = current.next;
        current.next = node;
      } else {
        this.tail.next = node;
        this.tail = node;
      }
    }
    return this;
  }

  delete(value: string, compare: Function) {
    if (!this.head) return null;

    let deleteNode: LinkNode | null = null;

    let current = this.head;

    while (current) {
      if (compare(current.value, value)) {
        deleteNode = current;
        current.next = current.next.next;

        if (current === this.head) {
          this.head = current.next;
        }
      } else {
        current = current.next;
      }
    }

    return deleteNode;
  }

  find(value: string, compare: Function) {
    if (!this.head) return null;

    let current = this.head;

    while (current) {
      if (compare(current.value, value)) {
        return current;
      } else {
        current = current.next;
      }
    }
    return null;
  }

  fromArray(array: string[]) {
    array.forEach((value) => this.append(value));
    return this;
  }

  toArray() {
    const nodes: any = [];
    let current = this.head;
    while (current) {
      nodes.push(current);
      current = current.next;
    }
    return nodes;
  }
}