Skip to content

Commit c581ec1

Browse files
Merge pull request #2971 from coopers/0021
Update 0021-merge-two-sorted-lists.py
2 parents 8578dd8 + 3e8f1a2 commit c581ec1

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

python/0021-merge-two-sorted-lists.py

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,32 @@
33
# def __init__(self, val=0, next=None):
44
# self.val = val
55
# self.next = next
6+
7+
# Iterative
68
class Solution:
79
def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode:
8-
dummy = ListNode()
9-
tail = dummy
10+
dummy = node = ListNode()
1011

1112
while list1 and list2:
1213
if list1.val < list2.val:
13-
tail.next = list1
14+
node.next = list1
1415
list1 = list1.next
1516
else:
16-
tail.next = list2
17+
node.next = list2
1718
list2 = list2.next
18-
tail = tail.next
19+
node = node.next
1920

20-
if list1:
21-
tail.next = list1
22-
elif list2:
23-
tail.next = list2
21+
node.next = list1 or list2
2422

2523
return dummy.next
24+
25+
# Recursive
26+
class Solution:
27+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
28+
if not list1:
29+
return list2
30+
if not list2:
31+
return list1
32+
lil, big = (list1, list2) if list1.val < list2.val else (list2, list1)
33+
lil.next = self.mergeTwoLists(lil.next, big)
34+
return lil

0 commit comments

Comments
 (0)