-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathsol.py
44 lines (39 loc) · 1.22 KB
/
sol.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
42
43
44
import heapq
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
def __str__(self):
curr = self
string = ''
while curr is not None:
if curr.next is not None:
string+='{}-->'.format(curr.val)
else:
string+='{}-->NULL'.format(curr.val)
curr = curr.next
return string
def mergeSortedLists(lsts: 'list(ListNode)') -> ListNode:
if lsts is None or len(lsts)==0:
return None
H = []
for i, lst in enumerate(lsts):
heapq.heappush(H, (lst.val, i))
merged_lst = ListNode('*')
curr = merged_lst
while len(H)>0:
val, idx = heapq.heappop(H)
curr.next = ListNode(val)
curr = curr.next
if lsts[idx].next is not None:
lsts[idx] = lsts[idx].next
heapq.heappush(H, (lsts[idx].val, idx))
return merged_lst.next
def main():
lst1=ListNode(1); lst1.next=ListNode(4); lst1.next.next=ListNode(5)
lst2=ListNode(1); lst2.next=ListNode(3); lst2.next.next=ListNode(4)
lst3=ListNode(2); lst3.next=ListNode(6);
lst4=mergeSortedLists(lsts=[lst1, lst2, lst3])
print(lst4)
if __name__=='__main__':
main()