模拟

方法一递归

参考代码

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, val=0, next=None):
  4. # self.val = val
  5. # self.next = next
  6. class Solution:
  7. def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
  8. if not list1:
  9. return list2
  10. if not list2:
  11. return list1
  12. merge = None
  13. if list1.val < list2.val:
  14. merge = ListNode(list1.val)
  15. list1 = list1.next
  16. else:
  17. merge = ListNode(list2.val)
  18. list2 = list2.next
  19. merge.next = self.mergeTwoLists(list1,list2)
  20. return merge

复杂度分析

时间复杂度 O(n + m) n和n是链表的长度
空间复杂度 O(n + m) 主要是递归调用栈的开销

方法二迭代

参考代码

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, val=0, next=None):
  4. # self.val = val
  5. # self.next = next
  6. class Solution:
  7. def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
  8. pre = ListNode()
  9. cur = pre
  10. while list1 or list2:
  11. if not list1:
  12. cur.next = list2
  13. break
  14. if not list2:
  15. cur.next = list1
  16. break
  17. if list1.val < list2.val:
  18. cur.next = list1
  19. list1 = list1.next
  20. else:
  21. cur.next = list2
  22. list2 = list2.next
  23. cur = cur.next
  24. return pre.next

复杂度分析

时间复杂度 O(n + m) n和n是链表的长度
空间复杂度 O(1)