# Merge K Sorted Lists (LC version 3.02).
from heapq import heappush, heappop
# List.
class ListNode:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
def makeList(seq):
l = None
for x in reversed(seq):
l = ListNode(x, l)
return l
def printList(l):
a = []
while l:
a.append(l.val)
l = l.next
print('List(', a, ')', sep='')
# Merge.
def mergeKLists(lists):
#
# Add lists to heap keyed on node.val; a second integer key is used
# and serves a dual purpose:
# 1. The unique keys prevent the comparison from reaching the node
# element, which is not comparable.
# 2. The keys are ordered ascending with respect to the list input,
# ensuring stability for equal valued elements.
#
heap = []
for k, n in enumerate(lists):
if n:
heappush(heap, (n.val, k, n))
#
# The heap maintains the smallest valued head node for all lists at
# its front. This node is appended to temp and replaced by its next
# node in the heap as the new list head. The loop exits when only a
# single list remains.
#
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]))
IyBNZXJnZSBLIFNvcnRlZCBMaXN0cyAoTEMgdmVyc2lvbiAzLjAyKS4KCmZyb20gaGVhcHEgaW1wb3J0IGhlYXBwdXNoLCBoZWFwcG9wCgojIExpc3QuCgpjbGFzcyBMaXN0Tm9kZToKICAgIGRlZiBfX2luaXRfXyhzZWxmLCB2YWw9Tm9uZSwgbmV4dD1Ob25lKToKICAgICAgICBzZWxmLnZhbCA9IHZhbAogICAgICAgIHNlbGYubmV4dCA9IG5leHQKCmRlZiBtYWtlTGlzdChzZXEpOgogICAgbCA9IE5vbmUKICAgIGZvciB4IGluIHJldmVyc2VkKHNlcSk6CiAgICAgICAgbCA9IExpc3ROb2RlKHgsIGwpCiAgICByZXR1cm4g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vcCBleGl0cyB3aGVuIG9ubHkgYQogICAgIyBzaW5nbGUgbGlzdCByZW1haW5zLgogICAgIwoKICAgIHRlbXAgPSBMaXN0Tm9kZSgpCiAgICBpZiBoZWFwOgogICAgICAgIHQgPSB0ZW1wCiAgICAgICAgd2hpbGUgVHJ1ZToKICAgICAgICAgICAgXywgaywgbiA9IGhlYXBwb3AoaGVhcCkKICAgICAgICAgICAgdC5uZXh0ID0gbgogICAgICAgICAgICBpZiBub3QgaGVhcDoKICAgICAgICAgICAgICAgIGJyZWFrCiAgICAgICAgICAgIHQgPSB0Lm5leHQKICAgICAgICAgICAgbiA9IG4ubmV4dAogICAgICAgICAgICBpZiBuOgogICAgICAgICAgICAgICAgaGVhcHB1c2goaGVhcCwgKG4udmFsLCBrLCBuKSkKICAgIHJldHVybiB0ZW1wLm5leHQKCiMgU2hvdy4KCmwwID0gbWFrZUxpc3QoW10pCmwxID0gbWFrZUxpc3QoWzEsIDMsIDUsIDddKQpsMiA9IG1ha2VMaXN0KFsyLCA0LCA2XSkKbDMgPSBtYWtlTGlzdChbMCwgNCwgOF0pCgpwcmludExpc3QobDApCnByaW50TGlzdChsMSkKcHJpbnRMaXN0KGwyKQpwcmludExpc3QobDMpCgpwcmludExpc3QobWVyZ2VLTGlzdHMoW10pKQpwcmludExpc3QobWVyZ2VLTGlzdHMoW2wwXSkpCnByaW50TGlzdChtZXJnZUtMaXN0cyhbbDFdKSkKcHJpbnRMaXN0KG1lcmdlS0xpc3RzKFtsMSwgbDIsIGwzXSkp
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])