Skip to content

构造链表

下面的代码展示如何从一个数组构造一个链表。

Code

链表节点定义:

javascript
function ListNode(val, next) {
  this.val = val ? val : 0;
  this.next = next ? next : null;
}

生成链表:

javascript
function generateLinkedList(array) {
  let head = new ListNode(array[0]);
  let curr = head;
  for (const n of array.slice(1)) {
    curr.next = new ListNode(n);
    curr = curr.next;
  }
  curr.next = null;
  return head;
}