-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path23.py
43 lines (35 loc) · 944 Bytes
/
23.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
33
34
35
36
37
38
39
40
41
42
43
import heapq
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if len(lists) == 0:
return None
heap = []
k = len(lists)
for i in range(k):
if lists[i] != None:
heap.append((lists[i].val, lists[i]))
heapq.heapify(heap)
ans = None
head = None
while (len(heap) > 0):
v, l = heapq.heappop(heap)
t = l.next
l.next = None
if head == None:
head = l
ans = head
else:
ans.next = l
ans = ans.next
if t != None:
heapq.heappush(heap, (t.val, t))
return head