# 运行时错误 - Leetcode 上的合并 k 个排序列表

[英]Runtime Error - Merge k Sorted Lists on Leetcode

``````Runtime Error
TypeError: [] is not valid value for the expected return type ListNode
raise TypeError(str(ret) + " is not valid value for the expected return type ListNode");
Line 65 in _driver (Solution.py)
_driver()
Line 71 in <module> (Solution.py)
``````

``````# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if not lists: return lists
if len(lists) == 1: return lists[0]
# return itself if 'lists' is empty or only has one ListNode

dummy_last = ListNode(10**5)
# During comparison, if a linkedlist is out of nodes, assign dummy_last to be its last node. The maximum value of a listnode is 10**4, so dummy_last would be the largest.*
flag = 0

# Use all_values to contain the current listnodes' values of all Linked lists. For example, with lists = [[1,4,5],[1,3,4],[2,6]], all_values = [1, 1, 2]
all_values = []
for i in range(0, len(lists)):
all_values.append(lists[i].val)

while True:
min_value = min(all_values)
if min_value == 10**5: break # Finished merging of all linked lists
min_index = all_values.index(min_value)

if flag == 0: # To decide if it's the first node of our answer linked list to assign the "head"
dummy_front = lists[min_index]
flag = 1
else:
dummy_front.next = lists[min_index]
dummy_front = dummy_front.next
all_values.pop(min_index) # Pop the used smallest value
if not lists[min_index].next: # If the linked list has no other nodes, assign dummy_last to be its last node.
lists[min_index] = dummy_last

else:
lists[min_index] = lists[min_index].next
all_values.insert(min_index, lists[min_index].val) # Insert new value at min_index
``````

Leetcode 提供了一个例子：

``````Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
[
1->4->5,
1->3->4,
2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6
``````

``````class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
vals = []
for node in lists:
while node:
vals.append(node.val)
node = node.next
if not vals:
return
vals.sort()
result = ListNode(vals[0])
prev = result
for v in vals[1:]:
prev.next = ListNode(v)
prev = prev.next
return result
``````

``````if not lists: return lists
``````

``````    for i in range(0, len(lists)):
all_values.append(lists[i].val)
``````

`lists[i]`可能是`None` （表示一个空链表），在这种情况下`lists[i].val`是一个无效引用。 为避免这种情况，您最好先从`lists`删除所有空列表，就在 function 的顶部：

``````lists = list(filter(None, lists))
``````

``````        min_value = min(all_values)
``````

``````        min_index = all_values.index(min_value)
``````

### 分而治之

``````def mergeTwoLists(list1, list2):
while list1 and list2:
if list1.val < list2.val:
result.next = list1
list1 = list1.next
else:
result.next = list2
list2 = list2.next
result = result.next
result.next = list1 or list2

def mergeLists(lists):
if len(lists) <= 2:  # base case of recursion
return lists[0] if len(lists) == 1 else mergeTwoLists(*lists)
mid = len(lists) // 2
return mergeTwoLists(mergeLists(lists[:mid]), mergeLists(lists[mid:]))

class Solution:
def mergeKLists(self, lists):
if lists:
return mergeLists(lists)
``````