yan chuanli 2 years ago
parent
commit
897c67811e
2 changed files with 69 additions and 22 deletions
  1. 26 22
      merge_two_lists.py
  2. 43 0
      utils.py

+ 26 - 22
merge_two_lists.py

@@ -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]

+ 43 - 0
utils.py

@@ -0,0 +1,43 @@
+import pytest
+
+
+def arr_to_linklist(arr):
+
+    p = None
+    for n in reversed(arr):
+        node = ListNode(n)
+        node.next = p
+        p = node
+    return p
+
+def linkList_to_arr(head):
+    res = []
+    cur = head
+    while cur is not None:
+        res.append(cur.val)
+        cur = cur.next
+
+    return res
+
+def list_to_linklist(arr):
+    head = ListNode(arr[0])
+    p = head
+    for i in range(1, len(arr)):
+        p.next = ListNode(arr[i])
+        p = p.next
+    return head
+
+
+class ListNode:
+    def __init__(self, val=0, next=None):
+        self.val = val
+        self.next = next
+
+
+
+
+def test_arr_to_linklist():
+    arr = [1, 3, 4, 5, 6]
+    head = arr_to_linklist(arr)
+    arr1 = linkList_to_arr(head)
+    assert  arr == arr1