Skip to content

Commit 6966f62

Browse files
committed
added 0021_merge_two_sorted_lists.py
1 parent b8bc7c0 commit 6966f62

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""
2+
You are given the heads of two sorted linked lists list1 and list2.
3+
4+
Merge the two lists in a one sorted list. The list should be made
5+
by splicing together the nodes of the first two lists.
6+
7+
Return the head of the merged linked list.
8+
Example 1:
9+
Input: list1 = [1,2,4], list2 = [1,3,4]
10+
Output: [1,1,2,3,4,4]
11+
12+
Example 2:
13+
Input: list1 = [], list2 = []
14+
Output: []
15+
16+
Example 3:
17+
Input: list1 = [], list2 = [0]
18+
Output: [0]
19+
20+
Constraints:
21+
* The number of nodes in both lists is in the range [0, 50]
22+
* -100 <= Node.val <= 100
23+
* Both list1 and list2 are sorted in non-decreasing order
24+
"""
25+
26+
class Solution:
27+
# O(n+m)
28+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
29+
if list1 is None and list2 is None:
30+
return list1
31+
32+
dummy = current = ListNode()
33+
while list1 and list2:
34+
if list1.val < list2.val:
35+
current.next = list1
36+
list1 = list1.next
37+
else:
38+
current.next = list2
39+
list2 = list2.next
40+
current = current.next
41+
42+
if list1 is None:
43+
current.next = list2
44+
45+
if list2 is None:
46+
current.next = list1
47+
48+
return dummy.next

0 commit comments

Comments
 (0)