Skip to content

Commit cb95cde

Browse files
committed
Add Iterative along with Recursive solution
1 parent b8beb67 commit cb95cde

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

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

+20
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
# def __init__(self, val=0, next=None):
44
# self.val = val
55
# self.next = next
6+
7+
# Recursive
68
class Solution:
79
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
810
if not list1:
@@ -12,3 +14,21 @@ def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) ->
1214
lil, big = (list1, list2) if list1.val < list2.val else (list2, list1)
1315
lil.next = self.mergeTwoLists(lil.next, big)
1416
return lil
17+
18+
# Iterative
19+
class Solution:
20+
def mergeTwoLists(self, list1: ListNode, list2: ListNode) -> ListNode:
21+
dummy = node = ListNode()
22+
23+
while list1 and list2:
24+
if list1.val < list2.val:
25+
node.next = list1
26+
list1 = list1.next
27+
else:
28+
node.next = list2
29+
list2 = list2.next
30+
node = node.next
31+
32+
node.next = list1 or list2
33+
34+
return dummy.next

0 commit comments

Comments
 (0)