# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param lists ListNode类一维数组
# @return ListNode类
#
class Solution:
def merge(self, pHead1: ListNode, pHead2: ListNode) -> ListNode:
if not pHead1:
return pHead2
if not pHead2:
return pHead1
head = ListNode(-1)
cur = head
while pHead1 and pHead2:
if pHead1.val <= pHead2.val:
cur.next = pHead1
pHead1 = pHead1.next
else:
cur.next = pHead2
pHead2 = pHead2.next
cur = cur.next
if pHead1:
cur.next = pHead1
else:
cur.next = pHead2
return head.next
def divideList(self, lists: list[ListNode], left: int, right: int):
if left > right:
return None
elif left == right:
return lists[left]
mid = int((left + right) / 2)
return self.merge(
self.divideList(lists, left, mid), self.divideList(lists, (mid + 1), right)
)
def mergeKLists(self, lists: list[ListNode]) -> ListNode:
# write code here
return self.divideList(lists, 0, len(lists) - 1)