forked from kanchanachathuranga/Hacktoberfest-2022-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMerge k Sorted Lists.py
29 lines (23 loc) · 970 Bytes
/
Merge k Sorted Lists.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
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
if lists == None or len(lists) == 0:
return None
dummy = ListNode(-1)
tail = dummy
heap = []
#Pushing first values to the heap
for i in range(len(lists)):
if lists[i]:
heappush(heap, (lists[i].val, i))
while heap:
# Poping out the value and index
temp, i = heappop(heap)
# Creating a new node and adding to tail and updating tail
tail.next = ListNode(temp)
tail = tail.next
# Updating the org Linked List with its Next value ( it will remove the value used)
lists[i] = lists[i].next
if lists[i]:
# Pushing the value to the LL
heappush(heap, (lists[i].val, i))
return dummy.next