调用heapq函数,先将所有的数据放入到堆中,再对列表进行排序,最后再通过链表进行连接
# 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[ListNode]
:rtype: ListNode
"""
import heapq
p = ListNode(0)
cur = p
head = []
for i in range(len(lists)):
h = lists[i]
while h:
heapq.heappush(head, h.val)
h = h.next
head.sort(reverse=True)
while head:
cur.next = ListNode(head.pop())
cur = cur.next
return p.next