Skip to content
On this page

解题

将两个升序链表合并为一个新的 升序 链表并返回。

新链表是通过拼接给定的两个链表的所有节点组成的。

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

在自己解题的时候有个疑问,对比然后往后排,我感觉没什么问题,但是一直报错TypeError: Cannot read properties of null (reading 'val')

typescript
function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
  let cur = new ListNode();
  let res = cur;

  while (list1 && list2) {
    let temp = new ListNode();
    if (list1.val <= list2.val) {
      cur.val = list1.val;
      list1 = list1.next;
    }
    if (list1.val >= list2.val) {
      cur.val = list2.val;
      list2 = list2.next;
    }
    cur.next = temp;
    cur = temp;
  }

  if (list1) cur.next = list1;
  if (list2) cur.next = list2;
  return res;
}

不太懂为什么报错 虽然我写的问题很大

最终写出来的解法

typescript
function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
  let cur = new ListNode();
  let head = cur;

  while (list1 && list2) {
    if (list1.val < list2.val) {
      cur.next = list1;
      list1 = list1.next;
    } else {
      cur.next = list2;
      list2 = list2.next;
    }
    cur = cur.next;
  }

  if (list1) cur.next = list1;
  if (list2) cur.next = list2;
  return head.next;
}

递归解法(没想出来)

typescript
var mergeTwoLists = function (list1, list2) {
  if (list1 === null) return list2
  if (list2 === null) return list1
  function deep (l1, l2) {
    if (l1 === null) return l2
    if (l2 === null) return l1
    if (l1.val < l2.val) {
      l1.next = deep(l1.next, l2)
      return l1
    } else {
      l2.next = deep(l1, l2.next)
      return l2
    }
  }
  return deep(list1, list2)
};

作者:羊肉串
链接:https://leetcode.cn/problems/merge-two-sorted-lists/solutions/1389197/by-alexyang-5nj6/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。