11from data_structures .singly_linked_list_node import SinglyLinkedListNode
22
33
4- def merge_k_lists ( lists : list [ SinglyLinkedListNode [ int ]] ) -> SinglyLinkedListNode [ int ] | None :
4+ def merge_k_lists [ T ]( lists ) -> SinglyLinkedListNode | None :
55 """Merge K Sorted Lists.
66
77 You are given an array of k linked lists, each linked list sorted in ascending order.
@@ -11,32 +11,29 @@ def merge_k_lists(lists: list[SinglyLinkedListNode[int]]) -> SinglyLinkedListNod
1111 Repeatedly scans the current head of every list, appending the smallest one found each round.
1212 """
1313 dummy = SinglyLinkedListNode ()
14- current : SinglyLinkedListNode | None = dummy
14+ current : SinglyLinkedListNode = dummy
1515
1616 if not lists :
1717 return None
1818
19- lists = [val for val in lists if val ]
19+ filtered_lists : list [ SinglyLinkedListNode ] = [val for val in lists if val ]
2020
21- while lists :
22- min_node = None
21+ while filtered_lists :
22+ min_node = 0
2323 smallest = float ("inf" )
2424
25- for index , head in enumerate (lists ):
26- if head .data and smallest and head .data <= smallest :
25+ for index , head in enumerate (filtered_lists ):
26+ if head .data and head .data <= smallest :
2727 smallest = head .data
2828 min_node = index
2929
30- if min_node and current :
31- current .next = lists [min_node ]
32-
33- if not lists [min_node ].next :
34- lists .pop (min_node )
35- else :
36- next_node = lists [min_node ].next
37- if next_node :
38- lists [min_node ] = next_node
39- if current :
40- current = current .next
30+ node = filtered_lists [min_node ]
31+ current .next = node
32+
33+ if node .next :
34+ filtered_lists [min_node ] = node .next
35+ else :
36+ filtered_lists .pop (min_node )
37+ current = current .next
4138
4239 return dummy .next
0 commit comments