# Merge K Sorted Lists (LC version 3.04).
from heapq import heappush, heappop
# List.
class ListNode:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
def makeList(seq):
n = None
for x in reversed(seq):
n = ListNode(x, n)
return n
def printList(n):
a = []
while n:
a.append(n.val)
n = n.next
print('List(', a, ')', sep='')
# Merge.
def mergeKLists(lists):
# Push list heads to heap keyed on node.val and a secondary integer.
# The secondary keys serve 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))
if not heap:
return None
# The heap maintains the smallest valued head node for all lists at
# its front. The node is appended to the result and heap is updated
# with its next node as the new list head. The loop exits when only
# a single list remains.
temp = ListNode()
t = temp
while True:
_, k, n = heappop(heap)
t.next = n
if not heap:
return temp.next
t = t.next
n = n.next
if n:
heappush(heap, (n.val, k, n))
# 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]))
IyBNZXJnZSBLIFNvcnRlZCBMaXN0cyAoTEMgdmVyc2lvbiAzLjA0KS4KCmZyb20gaGVhcHEgaW1wb3J0IGhlYXBwdXNoLCBoZWFwcG9wCgojIExpc3QuCgpjbGFzcyBMaXN0Tm9kZToKICAgIGRlZiBfX2luaXRfXyhzZWxmLCB2YWw9Tm9uZSwgbmV4dD1Ob25lKToKICAgICAgICBzZWxmLnZhbCA9IHZhbAogICAgICAgIHNlbGYubmV4dCA9IG5leHQKCmRlZiBtYWtlTGlzdChzZXEpOgogICAgbiA9IE5vbmUKICAgIGZvciB4IGluIHJldmVyc2VkKHNlcSk6CiAgICAgICAgbiA9IExpc3ROb2RlKHgsIG4pCiAgICByZXR1cm4gbg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ZXh0IG5vZGUgYXMgdGhlIG5ldyBsaXN0IGhlYWQuIFRoZSBsb29wIGV4aXRzIHdoZW4gb25seQogICAgIyBhIHNpbmdsZSBsaXN0IHJlbWFpbnMuCgogICAgdGVtcCA9IExpc3ROb2RlKCkKICAgIHQgPSB0ZW1wCiAgICB3aGlsZSBUcnVlOgogICAgICAgIF8sIGssIG4gPSBoZWFwcG9wKGhlYXApCiAgICAgICAgdC5uZXh0ID0gbgogICAgICAgIGlmIG5vdCBoZWFwOgogICAgICAgICAgICByZXR1cm4gdGVtcC5uZXh0CiAgICAgICAgdCA9IHQubmV4dAogICAgICAgIG4gPSBuLm5leHQKICAgICAgICBpZiBuOgogICAgICAgICAgICBoZWFwcHVzaChoZWFwLCAobi52YWwsIGssIG4pKQoKIyBTaG93LgoKbDAgPSBtYWtlTGlzdChbXSkKbDEgPSBtYWtlTGlzdChbMSwgMywgNSwgN10pCmwyID0gbWFrZUxpc3QoWzIsIDQsIDZdKQpsMyA9IG1ha2VMaXN0KFswLCA0LCA4XSkKCnByaW50TGlzdChsMCkKcHJpbnRMaXN0KGwxKQpwcmludExpc3QobDIpCnByaW50TGlzdChsMykKCnByaW50TGlzdChtZXJnZUtMaXN0cyhbXSkpCnByaW50TGlzdChtZXJnZUtMaXN0cyhbbDBdKSkKcHJpbnRMaXN0KG1lcmdlS0xpc3RzKFtsMV0pKQpwcmludExpc3QobWVyZ2VLTGlzdHMoW2wxLCBsMiwgbDNdKSk=
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])