-
Notifications
You must be signed in to change notification settings - Fork 0
/
23-MergeKSortedLists.py
41 lines (31 loc) · 1.04 KB
/
23-MergeKSortedLists.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import heapq
class HeapNode:
def __init__(self, node):
self.node = node
def __lt__(self, heap_node):
return self.node.val < heap_node.node.val
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
heap = []
head = None
curr = None
for ll_head in lists:
if ll_head is not None:
heapq.heappush(heap, HeapNode(ll_head))
while len(heap):
heap_node = heapq.heappop(heap)
ll_node = heap_node.node
if ll_node.next is not None:
heapq.heappush(heap, HeapNode(ll_node.next))
if head is None:
head = ll_node
curr = ll_node
else:
curr.next = ll_node
curr = curr.next
return head