File tree Expand file tree Collapse file tree 1 file changed +19
-15
lines changed
0021-merge-two-sorted-lists Expand file tree Collapse file tree 1 file changed +19
-15
lines changed Original file line number Diff line number Diff line change 1- # Approach 1: Recursion
2-
1+ # Approach 2: Iteration
2+
33# Time: O(n + m)
4- # Space: O(n + m )
4+ # Space: O(1 )
55
66# Definition for singly-linked list.
77# class ListNode:
88# def __init__(self, val=0, next=None):
99# self.val = val
1010# self.next = next
11-
1211class Solution :
1312 def mergeTwoLists (self , list1 : Optional [ListNode ], list2 : Optional [ListNode ]) -> Optional [ListNode ]:
14-
15- if list1 is None :
16- return list2
17- elif list2 is None :
18- return list1
19- elif list1 .val < list2 .val :
20- list1 .next = self .mergeTwoLists (list1 .next , list2 )
21- return list1
22- else :
23- list2 .next = self .mergeTwoLists (list1 , list2 .next )
24- return list2
13+ prehead = ListNode (- 1 )
14+ prev = prehead
15+
16+ while list1 and list2 :
17+ if list1 .val <= list2 .val :
18+ prev .next = list1
19+ list1 = list1 .next
20+ else :
21+ prev .next = list2
22+ list2 = list2 .next
23+ prev = prev .next
24+
25+ # At least one of l1 and l2 can still have nodes at this point, so connect the non-null list to the end of the merged list.
26+ prev .next = list1 if list1 is not None else list2
27+
28+ return prehead .next
2529
You can’t perform that action at this time.
0 commit comments