双向链表

Published: · LastMod: April 07, 2024 · 289 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
class Node {
  constructor(value) {
    this.prev = null;
    this.value = value;
    this.next = null;
  }
}

class DoublyLinkedList {
  constructor() {
    this.head = null;
    this.tail = null;
  }

  add(value) {
    const node = new Node(value);
    if (!this.head) {
      this.head = node;
      this.tail = node;
    } else {
      node.prev = this.tail;
      this.tail.next = node;
      this.tail = node;
    }
  }

  delete(value) {
    if (!this.head) return null;

    let current = this.head;
    let deleteNode = null;

    while (current) {
      if (current.value === value) {
        deleteNode = current;

        if (deleteNode === this.head) {
          this.head = deleteNode.next;
          if (this.head.prev) {
            this.head.prev = null;
          }
          if (node === this.tail) {
            this.tail = null;
          }
        } else if (deleteNode === this.tail) {
          this.tail = deleteNode.prev;
          this.tail.next = null;
        } else {
          let prev = deleteNode.prev;
          let next = deleteNode.next;
          prev.next = next.next;
          next.prev = prev;
        }
      }
      current = current.next;
    }
  }

  prepend(value) {
    const node = new Node(value);
    if (!this.head) {
      this.head = node;
      this.tail = node;
    } else {
      node.next = this.head;
      this.head.prev = node;
      this.head = node;
    }
  }

  find(value) {
    if (!this.head) return null;

    let current = this.head;

    while (current) {
      if (current.value === value) return current;
      current = current.next;
    }

    return null;
  }
}