将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
提示:
- 两个链表的节点数目范围是
[0, 50]
-100 <= node.val <="100
=>
l1
和 l2
均按 非递减顺序 排列
非递归
增加一个节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: head = ListNode() p = head while list1 and list2: if list1.val <= list2.val: p.next = list1 p = p.next list1 = list1.next else: p.next = list2 p = p.next list2 = list2.next if not list1: p.next = list2 else: p.next = list1 return head.next
|
list2插入list1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: """执行用时:44 ms, 在所有 Python3 提交中击败了43.43%的用户 内存消耗:15.1 MB, 在所有 Python3 提交中击败了22.66%的用户""" p = ListNode(0,None) p.next = list1 q = p while list1 is not None and list2 is not None: if list1.val > list2.val: q.next = ListNode(list2.val,list1) list2 = list2.next q = q.next else: q = q.next list1 = list1.next if list1 is None: q.next = list2 return p.next
|
递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: """ 执行用时:32 ms, 在所有 Python3 提交中击败了96.98%的用户 内存消耗:15.3 MB, 在所有 Python3 提交中击败了5.12%的用户 """ if list1 is None: return list2 elif list2 is None: return list1 else: if list1.val < list2.val: list1.next = self.mergeTwoLists(list1.next,list2) return list1 else: list2.next = self.mergeTwoLists(list1,list2.next) return list2
|