我有一个关于这个链表合并代码如何工作的快速问题

我对 head.next 如何返回整个列表而不是下一个值感到困惑,例如下面的代码中的 l1,l2,dummy .next。特别是我想知道 head.next 如何返回整个排序数组并跳过在第二行输入的 -1 值。


let mergeTwoLists = function (l1, l2) {

  let dummy = new ListNode(-1);

  let head = dummy;


  while (l1 !== null && l2 !== null) {

    if (l1.val <= l2.val) {

      dummy.next = l1;

      l1 = l1.next;

    } else {

      dummy.next = l2;

      l2 = l2.next;

    }

    dummy = dummy.next;

  }


  if (l1 !== null) {

    dummy.next = l1;

  } else {

    dummy.next = l2;

  }


  return head.next;

};


class ListNode {

  constructor(val = null, next = null) {

    this.val = val;

    this.next = next;

  }

}


沧海一幻觉
浏览 119回答 1
1回答

aluckdog

可视化列表的构建方式可能会有所帮助:让输入是一个列表,其中包含值 [3, 9] 和另一个只有 [4] 的列表:&nbsp;l1&nbsp;↓&nbsp;3 → 9 → null&nbsp;l2&nbsp;↓&nbsp;4 → null在循环开始之前创建一个新节点:head&nbsp;↓-1&nbsp;↑dummy循环将进行第一次迭代,并且if条件为真。首先dummmy.next是适配,导致出现这种情况:head l1&nbsp;↓&nbsp; &nbsp;↓-1 → 3 → 9 → null&nbsp;↑dummy&nbsp; &nbsp;&nbsp;&nbsp;l2&nbsp;↓&nbsp;4 → null...然后l1重新分配一个新的参考:head&nbsp; &nbsp; &nbsp;l1&nbsp;↓&nbsp; &nbsp; &nbsp; &nbsp;↓-1 → 3 → 9 → null&nbsp;↑dummy&nbsp; &nbsp;&nbsp;&nbsp;l2&nbsp;↓&nbsp;4 → null循环中的最后一条语句为 分配了一个新引用dummy:head&nbsp; &nbsp; &nbsp;l1&nbsp;↓&nbsp; &nbsp; &nbsp; &nbsp;↓-1 → 3 → 9 → null&nbsp; &nbsp; &nbsp;↑&nbsp; &nbsp; dummy&nbsp; &nbsp;&nbsp;&nbsp;l2&nbsp;↓&nbsp;4 → null循环第二次迭代,if现在条件为假,所以我们进入else代码块。Firstdummmy.next被改编(这打破了它与 的链接l1,所以我移动了l1和的可视化l2):head&nbsp; &nbsp; &nbsp;l2&nbsp;↓&nbsp; &nbsp; &nbsp; &nbsp;↓-1 → 3 → 4 → null&nbsp; &nbsp; &nbsp;↑&nbsp; &nbsp; dummy&nbsp; &nbsp;&nbsp;&nbsp;l1&nbsp;↓&nbsp;9 → null...然后l1重新分配一个新的引用,在这种情况下它变成null:head&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; l2&nbsp;↓&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ↓-1 → 3 → 4 → null&nbsp; &nbsp; &nbsp;↑&nbsp; &nbsp; dummy&nbsp; &nbsp;&nbsp;&nbsp;l1&nbsp;↓&nbsp;9 → null循环中的最后一条语句为 分配了一个新引用dummy:head&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; l2&nbsp;↓&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ↓-1 → 3 → 4 → null&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;↑&nbsp; &nbsp; &nbsp; &nbsp; dummy&nbsp; &nbsp;&nbsp;&nbsp;l1&nbsp;↓&nbsp;9 → null在此阶段,循环条件不再为真 ( l2is null),因此if执行循环后面的块。这dummy.next与其余(不是null)参考链接。同样,为了可视化,我交换了l1和的位置l2:head&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;l1&nbsp;↓&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;↓-1 → 3 → 4 → 9 → null&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;↑&nbsp; &nbsp; &nbsp; &nbsp; dummy&nbsp; &nbsp;&nbsp;&nbsp;l2&nbsp;↓null现在我们到了最后的声明:return head.next。请注意headdid 从未离开在开始时创建的新节点。所以返回的引用是:head&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;l1&nbsp;↓&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;↓-1 → 3 → 4 → 9 → null&nbsp; &nbsp; &nbsp;↑&nbsp; &nbsp; returned&nbsp; &nbsp;&nbsp;&nbsp;l2&nbsp;↓null注意head在这个函数的整个执行过程中如何一直指向带有 -1 的节点。head值为 -1 的临时节点将被垃圾回收,因为一旦函数返回(是局部变量) ,就没有变量再引用它。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript