|
@@ -1,29 +1,33 @@
|
|
|
from typing import Optional
|
|
|
-import pytest
|
|
|
-# from Cython.Compiler.ExprNodes import ListNode
|
|
|
+from utils import ListNode
|
|
|
|
|
|
-class ListNode:
|
|
|
- def __init__(self, val=0, next=None):
|
|
|
- self.val = val
|
|
|
- self.next = next
|
|
|
|
|
|
class Solution:
|
|
|
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
|
|
|
- newList = ListNode()
|
|
|
- pre = newList
|
|
|
- if list1 and list2:
|
|
|
- if list1.val <= list2.val:
|
|
|
- pre.next = list1
|
|
|
- list1 = list1.next
|
|
|
- else:
|
|
|
- pre.next = list2
|
|
|
- list2 = list2.next
|
|
|
+ # 递归
|
|
|
+ list3 = ListNode()
|
|
|
+ head = list3
|
|
|
|
|
|
- pre = pre.next
|
|
|
+ # 非递归
|
|
|
+ # list3 = ListNode()
|
|
|
+ # pre = list3
|
|
|
+ # while list1 and list2:
|
|
|
+ # if list1.val <= list2.val:
|
|
|
+ # pre.next = list1
|
|
|
+ # list1 = list1.next
|
|
|
+ # else:
|
|
|
+ # pre.next = list2
|
|
|
+ # list2 = list2.next
|
|
|
+ #
|
|
|
+ # pre = pre.next
|
|
|
+ # pre.next = list1 if list1 else list2
|
|
|
+ # return list3.next
|
|
|
|
|
|
- pre.next = list1 if list1 else list2
|
|
|
-
|
|
|
- return newList
|
|
|
-
|
|
|
-if __name__ == "__main__":
|
|
|
- print(mergeTwoLists([1, 2, 4], [1, 3, 4]))
|
|
|
+# if __name__ == "__main__":
|
|
|
+# s = Solution()
|
|
|
+# l1 = arr_to_linklist([1, 2, 4])
|
|
|
+# l2 = arr_to_linklist([1, 3, 4])
|
|
|
+# l3 = s.mergeTwoLists(l1, l2)
|
|
|
+# res = linkList_to_arr(l3)
|
|
|
+# print(res)
|
|
|
+# assert res == [1,1,2,3,4,4]
|