Skip to content

Commit 3bdc80f

Browse files
committed
merge two sorted lists solution
1 parent 7fd579d commit 3bdc80f

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

merge-two-sorted-lists/devyejin.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
7+
8+
"""
9+
time : O(m+n)
10+
space : O(1)
11+
"""
12+
13+
14+
class Solution:
15+
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
16+
dummy = ListNode(None)
17+
18+
node = dummy
19+
20+
while list1 and list2:
21+
if list1.val <= list2.val:
22+
node.next = list1
23+
list1 = list1.next
24+
else:
25+
node.next = list2
26+
list2 = list2.next
27+
node = node.next
28+
node.next = list1 or list2
29+
30+
return dummy.next

0 commit comments

Comments
 (0)