Skip to content

Commit b8beb67

Browse files
committed
Use recursion to minimize the code and it is surprisingly fast.
1 parent 42a2695 commit b8beb67

File tree

1 file changed

+8
-19
lines changed

1 file changed

+8
-19
lines changed

Diff for: python/0021-merge-two-sorted-lists.py

+8-19
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,11 @@
44
# self.val = val
55
# self.next = next
66
class Solution:
7-
def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode:
8-
dummy = ListNode()
9-
tail = dummy
10-
11-
while list1 and list2:
12-
if list1.val < list2.val:
13-
tail.next = list1
14-
list1 = list1.next
15-
else:
16-
tail.next = list2
17-
list2 = list2.next
18-
tail = tail.next
19-
20-
if list1:
21-
tail.next = list1
22-
elif list2:
23-
tail.next = list2
24-
25-
return dummy.next
7+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
8+
if not list1:
9+
return list2
10+
if not list2:
11+
return list1
12+
lil, big = (list1, list2) if list1.val < list2.val else (list2, list1)
13+
lil.next = self.mergeTwoLists(lil.next, big)
14+
return lil

0 commit comments

Comments
 (0)