Merge k Sorted Lists LeetCode solution in Python
1# Definition for singly-linked list.2# class ListNode:3# def __init__(self, val=0, next=None):4# self.val = val5# self.next = next6from heapq import heappush, heappop789class Solution:10def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:11heap = []12heapq.heapify(heap)13start = end = ListNode(-1)14for i in lists:15if i:16heappush(heap, (i.val, id(i), i))17while heap:18val, iD, node = heappop(heap)19end.next = node20node = node.next21end = end.next22if node:23heappush(heap, (node.val, id(node), node))2425return start.next