Simple Python solution based on Priority Queue


  • 0
    C

    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 = node.next
            if len(queue) == 0:
                return None
            val = heapq.heappop(queue)
            head = previous = ListNode(val)
            while True:
                try:
                    v = heapq.heappop(queue)
                except IndexError:
                    break
                curr = ListNode(v)
                previous.next = 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.