合并k个链表,使用堆结构。
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
import heapq
pq = []
for i in range(len(lists)):
if lists[i]:
# 此处调用.val,注意需要先判定node不为空
heapq.heappush(pq, (lists[i].val, lists[i]))
dummy = ListNode(-1)
cur = dummy
while pq:
pair = heapq.heappop(pq)
_, root = pair
cur.next = root
cur = cur.next
if root.next:
heapq.heappush(pq, (root.next.val, root.next))
return dummy.next