JavaScript 实现链表

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

    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;
    }
欢迎通过「邮件」或者点击「这里」告诉我你的想法
Welcome to tell me your thoughts via "email" or click "here"