from operator import attrgetter
class Solution:
# @param a list of ListNode
# @return a ListNode
def mergeKLists(self, lists):
sorted_list = []
for head in lists:
curr = head
while curr is not None:
sorted_list.append(curr)
curr = curr.next
sorted_list = sorted(sorted_list, key=attrgetter('val'))
for i, node in enumerate(sorted_list):
try:
node.next = sorted_list[i + 1]
except:
node.next = None
if sorted_list:
return sorted_list[0]
else:
return None
Python 133ms solution


@Tony_Zhao I thought it just make reference to "ListNode" object when creating list, so only several pointers are created

@duke8253
This made more sense to me for the second half, and is a little cleaner:for i in range(len(sorted_list)  1): sorted_list[i].next = sorted_list[i + 1] return sorted_list[0] if sorted_list else None
Similar nonetheless!