mycode 91.2%
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ res = [] for li in lists: while li: res.append(li.val) li = li.next if not res : return None res = sorted(res) print(res) length = len(res) i = 0 dummy = head = ListNode(-1) while i < length: head.next = ListNode(res[i]) head = head.next i += 1 return dummy.next
但是下面的这个代码最后的链表就只有1一个val
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ res = [] for li in lists: while li: res.append(li.val) li = li.next if not res : return None res = sorted(res) print(res) length = len(res) i = 0 dummy = head = ListNode(res[0]) head = head.next while i < length - 1: i += 1 #print(i) head = ListNode(res[i]) #print(head.val) head = head.next return dummy
Input:[[1,4,5],[1,3,4],[2,6]]
Output:[1]
Expected:[1,1,2,3,4,4,5,6]
Stdout:[1, 1, 2, 3, 4, 4, 5, 6]
参考
class Solution: def mergeKLists(self, lists): nums, dum = [], ListNode(0) p = dum for l in lists: while l: nums.append(l) l = l.next for i in sorted(nums, key = lambda l: l.val): p.next = i p = p.next return dum.next