merge_two_lists.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from typing import Optional
  2. from utils import ListNode, arr_to_linklist, linkList_to_arr
  3. import pytest
  4. class Solution:
  5. def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
  6. # 递归
  7. if not list1:
  8. return list2
  9. elif not list2:
  10. return list1
  11. elif list1.val <= list2.val:
  12. list1.next = self.mergeTwoLists(list1.next, list2)
  13. return list1
  14. else:
  15. list2.next = self.mergeTwoLists(list2.next, list1)
  16. return list2
  17. # 非递归
  18. # list3 = ListNode()
  19. # pre = list3
  20. # while list1 and list2:
  21. # if list1.val <= list2.val:
  22. # pre.next = list1
  23. # list1 = list1.next
  24. # else:
  25. # pre.next = list2
  26. # list2 = list2.next
  27. #
  28. # pre = pre.next
  29. # pre.next = list1 if list1 else list2
  30. # return list3.next
  31. if __name__ == "__main__":
  32. s = Solution()
  33. list1 = arr_to_linklist([1, 2, 4])
  34. list2 = arr_to_linklist([1, 3, 4])
  35. res = s.mergeTwoLists(list1, list2)
  36. res = linkList_to_arr(res)
  37. assert res == [1,1,2,3,4,4]