Skip to content

Commit 02f4961

Browse files
committed
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 17.8 MB (22.97%)
1 parent 6fca276 commit 02f4961

File tree

1 file changed

+19
-15
lines changed

1 file changed

+19
-15
lines changed
Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,29 @@
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-
1211
class 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

0 commit comments

Comments
 (0)