JavaScript 实现链表

https://www.freecodecamp.org/news/implementing-a-linked-list-in-javascript/

 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
class ListNode {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}
class Linkedlist {
  constructor(head=null) {
    this.head = head;
  }
}

let node1 = new ListNode(2);
let node2 = new ListNode(5);
node1.next = node2;

let list = new Linkedlist(node1);

console.log(list.head.next.data)

size() {
  let count = 0;
  let node = this.head;
  while (node) {
    count++;
    node = node.next;
  }
  return count;
}

clear() {
  this.head = null;
}

getLast() {
  let lastNode = this.head;
  if (lastNode) {
    while (lastNode.next) {
      lastNode = lastNode.next;
    }
  }
  return lastNode;
}

getFirst() {
  return this.head;
}

Layout of comment panels