# Merge K Sorted Lists (LC version 3.01).
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, ')', sep='')
# Merge.
def mergeKLists(lists):
heap = []
for k, n in enumerate(lists):
if n:
heappush(heap, (n.val, k, n))
temp = ListNode()
if heap:
t = temp
while True:
_, k, n = heappop(heap)
t.next = n
if not heap:
break
t = t.next
n = n.next
if n:
heappush(heap, (n.val, k, n))
return temp.next
# Show.
l0 = makeList([])
l1 = makeList([1, 3, 5, 7])
l2 = makeList([2, 4, 6])
l3 = makeList([0, 4, 8])
printList(l0)
printList(l1)
printList(l2)
printList(l3)
printList(mergeKLists([]))
printList(mergeKLists([l0]))
printList(mergeKLists([l1]))
printList(mergeKLists([l1, l2, l3]))
IyBNZXJnZSBLIFNvcnRlZCBMaXN0cyAoTEMgdmVyc2lvbiAzLjAxKS4KCmZyb20gaGVhcHEgaW1wb3J0IGhlYXBwdXNoLCBoZWFwcG9wCgojIExpc3QuCgpjbGFzcyBMaXN0Tm9kZToKICAgIGRlZiBfX2luaXRfXyhzZWxmLCB2YWw9Tm9uZSwgbmV4dD1Ob25lKToKICAgICAgICBzZWxmLnZhbCA9IHZhbAogICAgICAgIHNlbGYubmV4dCA9IG5leHQKCmRlZiBtYWtlTGlzdChzZXEpOgogICAgdCA9IE5vbmUKICAgIGZvciB4IGluIHJldmVyc2VkKHNlcSk6CiAgICAgICAgdCA9IExpc3ROb2RlKHgsIHQpCiAgICByZXR1cm4gdAoKZGVmIHByaW50TGlzdChsKToKICAgIGEgPSBbXQogICAgd2hpbGUgbDoKICAgICAgICBhLmFwcGVuZChsLnZhbCkKICAgICAgICBsID0gbC5uZXh0CiAgICBwcmludCgnTGlzdCgnLCBhLCAnKScsIHNlcD0nJykKCiMgTWVyZ2UuCgpkZWYgbWVyZ2VLTGlzdHMobGlzdHMpOgogICAgaGVhcCA9IFtdCiAgICBmb3IgaywgbiBpbiBlbnVtZXJhdGUobGlzdHMpOgogICAgICAgIGlmIG46CiAgICAgICAgICAgIGhlYXBwdXNoKGhlYXAsIChuLnZhbCwgaywgbikpCiAgICB0ZW1wID0gTGlzdE5vZGUoKQogICAgaWYgaGVhcDoKICAgICAgICB0ID0gdGVtcAogICAgICAgIHdoaWxlIFRydWU6CiAgICAgICAgICAgIF8sIGssIG4gPSBoZWFwcG9wKGhlYXApCiAgICAgICAgICAgIHQubmV4dCA9IG4KICAgICAgICAgICAgaWYgbm90IGhlYXA6CiAgICAgICAgICAgICAgICBicmVhawogICAgICAgICAgICB0ID0gdC5uZXh0CiAgICAgICAgICAgIG4gPSBuLm5leHQKICAgICAgICAgICAgaWYgbjoKICAgICAgICAgICAgICAgIGhlYXBwdXNoKGhlYXAsIChuLnZhbCwgaywgbikpCiAgICByZXR1cm4gdGVtcC5uZXh0CgojIFNob3cuCgpsMCA9IG1ha2VMaXN0KFtdKQpsMSA9IG1ha2VMaXN0KFsxLCAzLCA1LCA3XSkKbDIgPSBtYWtlTGlzdChbMiwgNCwgNl0pCmwzID0gbWFrZUxpc3QoWzAsIDQsIDhdKQoKcHJpbnRMaXN0KGwwKQpwcmludExpc3QobDEpCnByaW50TGlzdChsMikKcHJpbnRMaXN0KGwzKQoKcHJpbnRMaXN0KG1lcmdlS0xpc3RzKFtdKSkKcHJpbnRMaXN0KG1lcmdlS0xpc3RzKFtsMF0pKQpwcmludExpc3QobWVyZ2VLTGlzdHMoW2wxXSkpCnByaW50TGlzdChtZXJnZUtMaXN0cyhbbDEsIGwyLCBsM10pKQ==
List([])
List([1, 3, 5, 7])
List([2, 4, 6])
List([0, 4, 8])
List([])
List([])
List([1, 3, 5, 7])
List([0, 1, 2, 3, 4, 4, 5, 6, 7, 8])