from typing import List
classListNode:def__init__(self, val=0,next=None):
self.val = val
self.next=nextclassSolution:defresort(self,lists):
lists =[n for n in lists if n]iflen(lists)<=1:return lists
cur = lists[0].val
left =1
right =len(lists)-1while left<=right:
mid =(left+right)//2if lists[mid].val <= cur:
left = mid+1else:
right = mid-1
target =(left+right)//2return lists[1:target+1]+[lists[0]]+lists[target+1:]defmergeKLists(self, lists: List[ListNode])-> ListNode:
lists =[n for n in lists if n]ifnot lists:returnNone
lists.sort(key=lambda x:x.val)
head = ListNode(0)
cur = head
while lists:
cur.next= ListNode(lists[0].val)
cur = cur.next
lists[0]=lists[0].next
lists=self.resort(lists)return head.next#测试用例
L1=ListNode(1)
L1.next=ListNode(4)
L1.next.next=ListNode(5)
L2=ListNode(1)
L2.next=ListNode(3)
L2.next.next=ListNode(4)
L3=ListNode(2)
L3.next=ListNode(6)
S=Solution()
res=S.mergeKLists([L1,L2,L3])