Tianhe Gao

JavaScript 实现链表

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

 1    class ListNode {
 2      constructor(data) {
 3        this.data = data;
 4        this.next = null;
 5      }
 6    }
 7    class Linkedlist {
 8      constructor(head=null) {
 9        this.head = head;
10      }
11    }
12
13    let node1 = new ListNode(2);
14    let node2 = new ListNode(5);
15    node1.next = node2;
16
17    let list = new Linkedlist(node1);
18
19    console.log(list.head.next.data)
20
21    size() {
22      let count = 0;
23      let node = this.head;
24      while (node) {
25        count++;
26        node = node.next;
27      }
28      return count;
29    }
30
31    clear() {
32      this.head = null;
33    }
34
35    getLast() {
36      let lastNode = this.head;
37      if (lastNode) {
38        while (lastNode.next) {
39          lastNode = lastNode.next;
40        }
41      }
42      return lastNode;
43    }
44
45    getFirst() {
46      return this.head;
47    }

No notes link to this note

Welcome to tell me your thoughts via "email"
UP