A simple python solution using heapq

  • 1
    from heapq import *
    class Solution(object):
        def mergeKLists(self, lists):
            def generateVals():
                h = [(node.val, node) for node in lists if node]
                while h:
                    v, n = heappop(h)
                    yield v
                    n = n.next
                    if n: heappush(h, (n.val, n))
            beforeHead = n = ListNode(None)
            for v in generateVals():
                n.next = ListNode(v)
                n = n.next
            return beforeHead.next

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.