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;
}



如希望撰写评论,请发邮件至 me@tianhegao.com (直接点击邮箱可自动跳转至默认邮箱App,并填写收信人和邮件主题)或者点击这里在线留言,我会挑选对读者有价值的评论附加到文章末尾。



可通过以下渠道赞赏此文