Skip to content

Commit 63cb397

Browse files
committed
Solve: mergeTwoLists
1 parent 7157d23 commit 63cb397

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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+
# Space: O(N)
9+
# Time: O(N)
10+
dummy = ListNode(val=0, next=None)
11+
pointer = dummy
12+
while (list1 is not None) and (list2 is not None):
13+
if list1.val <= list2.val:
14+
pointer.next = ListNode(list1.val)
15+
list1 = list1.next
16+
else:
17+
pointer.next = ListNode(list2.val)
18+
list2 = list2.next
19+
pointer = pointer.next
20+
if list1 is not None:
21+
pointer.next = list1
22+
elif list2 is not None:
23+
pointer.next = list2
24+
25+
return dummy.next

0 commit comments

Comments
 (0)