-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path23.MergekSortedLists.py
32 lines (30 loc) · 1005 Bytes
/
23.MergekSortedLists.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
# 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 mergeKLists(self, lists):
"""
:type lists: List[Optional[ListNode]]
:rtype: Optional[ListNode]
"""
if not lists:
return None
if len(lists) == 1:
return lists[0]
mid = len(lists) // 2
left, right = self.mergeKLists(lists[0:mid]), self.mergeKLists(lists[mid:])
return self.mergeTwo(left, right)
def mergeTwo(self, first, second):
dummy = current = ListNode()
while first and second:
if first.val < second.val:
current.next = first
first = first.next
else:
current.next = second
second = second.next
current = current.next
current.next = first or second
return dummy.next