将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4
链表节点定义:
class ListNode: def __init__(self, x): self.val = x self.next = None迭代: 创建一个新的节点head,遍历两链表,每次比较节点所指的位置并将较小节点值赋给head后的节点,最终得到合并后的链表
class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: head = ListNode(None) s = head while l1 or l2: if l1 is None: s.next = l2 break if l2 is None: s.next = l1 break if l1.val > l2.val: s.next = ListNode(l2.val) l2 = l2.next else: s.next = ListNode(l1.val) l1 =l1.next s = s.next return head.next运行结果:通过 运行时间:48ms;内存消耗:13.7MB 时间复杂度:O(m+n);空间复杂度:O(1)
递归:我们可以递归地定义在两个链表里的 merge 操作(忽略边界情况,比如空链表等)两个链表头部较小的一个与剩下元素的 merge 操作结果合并。
class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if l1 is None: return l2 elif l2 is None: return l1 elif l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2运行结果:通过 运行时间:40ms;内存消耗:13.8MB 时间复杂度:O(n+m);空间复杂度:O(n+m)
参考链接: 迭代与递归的区别: https://blog.csdn.net/liuchaoxuan/article/details/79967578