Skip to content

Commit 8c9ccc4

Browse files
committed
Week 4
1 parent 5c80b37 commit 8c9ccc4

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

merge-two-sorted-lists/8804who.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
class Solution:
7+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
8+
sorted_list = []
9+
10+
while True:
11+
if list1 is None and list2 is None:
12+
break
13+
elif list1 is None:
14+
sorted_list.append(list2.val)
15+
list2 = list2.next
16+
elif list2 is None:
17+
sorted_list.append(list1.val)
18+
list1 = list1.next
19+
else:
20+
if list1.val > list2.val:
21+
sorted_list.append(list2.val)
22+
list2 = list2.next
23+
else:
24+
sorted_list.append(list1.val)
25+
list1 = list1.next
26+
27+
def get_node(idx):
28+
if idx < len(sorted_list):
29+
return ListNode(sorted_list[idx], get_node(idx+1))
30+
else:
31+
return None
32+
33+
answer= get_node(0)
34+
35+
return answer
36+

0 commit comments

Comments
 (0)