Skip to content

Latest commit

 

History

History
40 lines (29 loc) · 871 Bytes

25.合并两个排序的链表.md

File metadata and controls

40 lines (29 loc) · 871 Bytes

题目

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

思路

image

链表头部节点比较,取较小节点。

小节点的next等于小节点的next和大节点的较小值。

如此递归。

返回小节点。

考虑代码的鲁棒性,也是递归的终止条件,两个head为null的情况,取对方节点返回。

代码

    function Merge(pHead1, pHead2) {
      if (!pHead1) {
        return pHead2;
      }
      if (!pHead2) {
        return pHead1;
      }
      let head;
      if (pHead1.val < pHead2.val) {
        head = pHead1;
        head.next = Merge(pHead1.next, pHead2);
      } else {
        head = pHead2;
        head.next = Merge(pHead1, pHead2.next);
      }
      return head;
    }