- Use the heap sort, traverse the list, and place the value of the head pointer of the linked list and the head pointer itself as an element in the heap;
- After traversing the list in the first step, there is a maximum of n elements in the heap, and n is the length of the list;
- When the heap is not empty, remove the minimum value from the heap, then point the pointer to the next element and merge it into the heap;
- The 3rd step is to ensure that the heap is always O (n) size;
- The heap is empty to return the head node.
# Definition for singly-linked list.# class ListNode (object):# def __init__ (self, x):# self.val = x# self.next = NoneclassSolution (Object):defMergeklists ( Self, lists):""": Type Lists:list[listnode]: Rtype:listnode """ ImportHEAPQ Min_heap=[] ret=Head=ListNode (0) forK, Linkinch Enumerate(lists):ifLink:heapq.heappush (Min_heap, [Link.val, link]) whileMin_heap:cur=Heapq.heappop (MIN_HEAP) ret.Next =cur[-1] Ret=Ret.Next ifRet.Next: Heapq.heappush (Min_heap, [ret.Next. val, ret.Next])returnHead.Next
Python solution leetcode:23. Merge k Sorted Lists