Skip to content

Commit ec0af70

Browse files
Create 21.MergeTwoSortedLists.py
1 parent 52692a0 commit ec0af70

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Easy/21.MergeTwoSortedLists.py

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
'''
2+
Merge two sorted linked lists and return it as a new sorted
3+
list. The new list should be made by splicing together the
4+
nodes of the first two lists.
5+
6+
Example:
7+
Input: l1 = [1,2,4], l2 = [1,3,4]
8+
Output: [1,1,2,3,4,4]
9+
10+
Example:
11+
Input: l1 = [], l2 = []
12+
Output: []
13+
14+
Example:
15+
Input: l1 = [], l2 = [0]
16+
Output: [0]
17+
18+
Constraints:
19+
- The number of nodes in both lists is in the range
20+
[0, 50].
21+
- -100 <= Node.val <= 100
22+
- Both l1 and l2 are sorted in non-decreasing order.
23+
'''
24+
#Difficulty: Easy
25+
#208 / 208 test cases passed.
26+
#Runtime: 40 ms
27+
#Memory Usage: 14.3 MB
28+
29+
#Runtime: 40 ms, faster than 40.63% of Python3 online submissions for Merge Two Sorted Lists.
30+
#Memory Usage: 14.3 MB, less than 26.66% of Python3 online submissions for Merge Two Sorted Lists.
31+
32+
# Definition for singly-linked list.
33+
# class ListNode:
34+
# def __init__(self, val=0, next=None):
35+
# self.val = val
36+
# self.next = next
37+
38+
class Solution:
39+
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
40+
node1 = l1
41+
node2 = l2
42+
l3 = ListNode()
43+
node = l3
44+
while node:
45+
if node1 and node2 and node1.val > node2.val:
46+
node.next = node2
47+
node2 = node2.next
48+
elif node1:
49+
node.next = node1
50+
node1 = node1.next
51+
elif node2:
52+
node.next = node2
53+
node2 = node2.next
54+
node = node.next
55+
return l3.next

0 commit comments

Comments
 (0)