forked from DevOgabek/LeetCodePythonSolutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge_two_sorted_lists.py
More file actions
33 lines (26 loc) · 815 Bytes
/
merge_two_sorted_lists.py
File metadata and controls
33 lines (26 loc) · 815 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# Merge Two Sorted Lists
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def mergeTwoLists(self, list1, list2):
if not list1: return list2
if not list2: return list1
if list1.val < list2.val:
list1.next = self.mergeTwoLists(list1.next, list2)
return list1
else:
list2.next = self.mergeTwoLists(list1, list2.next)
return list2
list1 = ListNode(1)
list1.next = ListNode(2)
list1.next.next = ListNode(4)
list2 = ListNode(1)
list2.next = ListNode(3)
list2.next.next = ListNode(4)
solution = Solution()
merged_list = solution.mergeTwoLists(list1, list2)
while merged_list:
print(merged_list.val, end=" ")
merged_list = merged_list.next