-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path21_MergeTwoSortedLists.py
35 lines (31 loc) · 1023 Bytes
/
21_MergeTwoSortedLists.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeTwoLists(self, list1, list2):
"""
:type list1: Optional[ListNode]
:type list2: Optional[ListNode]
:rtype: Optional[ListNode]
"""
dummy = ListNode()
tail = dummy
# move through both lists and add the lesser value to the tail
# of our new list
while list1 and list2:
if list1.val <= list2.val:
tail.next = list1
list1 = list1.next
else:
tail.next = list2
list2 = list2.next
tail = tail.next
# at this point we've reached the end of one of the lists
# so just tack the remaining other list on at the end
if list1:
tail.next = list1
else:
tail.next = list2
return dummy.next