Simple Python solution based on Priority Queue

  • 0

    The idea is as simple as it get. Add all the nodes to the Priority Queue. Keep popping and linking nodes in the new list.

       def mergeKLists(self, lists):
            :type lists: List[ListNode]
            :rtype: ListNode
            if not lists or len(lists) == 0:
                return None
            queue = []
            for node in lists:
                while node:
                    heapq.heappush(queue, node.val)
                    node =
            if len(queue) == 0:
                return None
            val = heapq.heappop(queue)
            head = previous = ListNode(val)
            while True:
                    v = heapq.heappop(queue)
                except IndexError:
                curr = ListNode(v)
       = curr
                previous = curr
            return head

Log in to reply

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