Python / Simple Solution Using heapq.merge and Generators

  • 1
    import heapq
    class Solution(object):
        def mergeKLists(self, lists):
            :type lists: List[ListNode]
            :rtype: ListNode
            if not lists or not any(head for head in lists):
                return []
            def gen(node):
                while node:
                    nxt =
                    yield (node.val, node)
                    node = nxt
            lst_gen = heapq.merge(*[gen(head) for head in lists])
            _, head = next(lst_gen)
            pre = head
            for _, node in lst_gen:
       = node
                pre = node
            return head

Log in to reply

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