# Merge K Sorted Lists (LC version 3.00).
from heapq import heappush, heappop
# List.
class ListNode:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
def makeList(seq):
t = None
for x in reversed(seq):
t = ListNode(x, t)
return t
def printList(l):
a = []
while l:
a.append(l.val)
l = l.next
print('List:', a)
# Merge.
def mergeKLists(lists):
heap = []
for k, n in enumerate(lists):
if n:
heappush(heap, (n.val, k, n))
temp = ListNode()
t = temp
while heap:
_, k, n = heappop(heap)
t.next = n
t = t.next
n = n.next
if n:
heappush(heap, (n.val, k, n))
return temp.next
# Show.
l1 = makeList([1, 3, 5, 7])
l2 = makeList([2, 4, 6])
l3 = makeList([0, 4, 8])
printList(l1)
printList(l2)
printList(l3)
printList(mergeKLists([l1, l2, l3]))
IyBNZXJnZSBLIFNvcnRlZCBMaXN0cyAoTEMgdmVyc2lvbiAzLjAwKS4KCmZyb20gaGVhcHEgaW1wb3J0IGhlYXBwdXNoLCBoZWFwcG9wCgojIExpc3QuCgpjbGFzcyBMaXN0Tm9kZToKICAgIGRlZiBfX2luaXRfXyhzZWxmLCB2YWw9Tm9uZSwgbmV4dD1Ob25lKToKICAgICAgICBzZWxmLnZhbCA9IHZhbAogICAgICAgIHNlbGYubmV4dCA9IG5leHQKCmRlZiBtYWtlTGlzdChzZXEpOgogICAgdCA9IE5vbmUKICAgIGZvciB4IGluIHJldmVyc2VkKHNlcSk6CiAgICAgICAgdCA9IExpc3ROb2RlKHgsIHQpCiAgICByZXR1cm4gdAoKZGVmIHByaW50TGlzdChsKToKICAgIGEgPSBbXQogICAgd2hpbGUgbDoKICAgICAgICBhLmFwcGVuZChsLnZhbCkKICAgICAgICBsID0gbC5uZXh0CiAgICBwcmludCgnTGlzdDonLCBhKQoKIyBNZXJnZS4KCmRlZiBtZXJnZUtMaXN0cyhsaXN0cyk6CiAgICBoZWFwID0gW10KICAgIGZvciBrLCBuIGluIGVudW1lcmF0ZShsaXN0cyk6CiAgICAgICAgaWYgbjoKICAgICAgICAgICAgaGVhcHB1c2goaGVhcCwgKG4udmFsLCBrLCBuKSkKICAgIHRlbXAgPSBMaXN0Tm9kZSgpCiAgICB0ID0gdGVtcAogICAgd2hpbGUgaGVhcDoKICAgICAgICBfLCBrLCBuID0gaGVhcHBvcChoZWFwKQogICAgICAgIHQubmV4dCA9IG4KICAgICAgICB0ID0gdC5uZXh0CiAgICAgICAgbiA9IG4ubmV4dAogICAgICAgIGlmIG46CiAgICAgICAgICAgIGhlYXBwdXNoKGhlYXAsIChuLnZhbCwgaywgbikpCiAgICByZXR1cm4gdGVtcC5uZXh0CgojIFNob3cuCgpsMSA9IG1ha2VMaXN0KFsxLCAzLCA1LCA3XSkKbDIgPSBtYWtlTGlzdChbMiwgNCwgNl0pCmwzID0gbWFrZUxpc3QoWzAsIDQsIDhdKQoKcHJpbnRMaXN0KGwxKQpwcmludExpc3QobDIpCnByaW50TGlzdChsMykKcHJpbnRMaXN0KG1lcmdlS0xpc3RzKFtsMSwgbDIsIGwzXSkp
List: [1, 3, 5, 7]
List: [2, 4, 6]
List: [0, 4, 8]
List: [0, 1, 2, 3, 4, 4, 5, 6, 7, 8]