File tree Expand file tree Collapse file tree 1 file changed +28
-1
lines changed Expand file tree Collapse file tree 1 file changed +28
-1
lines changed Original file line number Diff line number Diff line change @@ -10,14 +10,41 @@ class Solution:
10
10
https://leetcode-cn.com/problems/merge-two-sorted-lists/
11
11
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
12
12
"""
13
- # 递归
14
13
def mergeTwoLists (self , l1 : ListNode , l2 : ListNode ) -> ListNode :
15
14
if not l1 :
16
15
return l2
17
16
18
17
if not l2 :
19
18
return l1
20
19
20
+ res = ListNode ()
21
+ pre = res
22
+ while l1 and l2 :
23
+ if l1 .val > l2 .val :
24
+ pre .next = l2
25
+ l2 = l2 .next
26
+ else :
27
+ pre .next = l1
28
+ l1 = l1 .next
29
+
30
+ pre = pre .next
31
+
32
+ if l1 :
33
+ pre .next = l1
34
+
35
+ if l2 :
36
+ pre .next = l2
37
+
38
+ return res .next
39
+
40
+ # 递归
41
+ def mergeTwoListsByRecursive (self , l1 : ListNode , l2 : ListNode ) -> ListNode :
42
+ if not l1 :
43
+ return l2
44
+
45
+ if not l2 :
46
+ return l1
47
+
21
48
if l1 .val <= l2 .val :
22
49
l1 .next = self .mergeTwoLists (l1 .next , l2 )
23
50
return l1
You can’t perform that action at this time.
0 commit comments