给定 k 个排序链表组成的列表,返回合并后的排序链表。

示例:

输入:

[  
  1->4->5,  
  1->3->4,  
  2->6  
] 

输出:

1->1->2->3->4->4->5->6  

解答:

def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
    if l1 is None : return l2
    if l2 is None : return l1
    if l1.val<= l2.val:
        res = l1
        l1 = l1.next
        res.next = self.mergeTwoLists(l1,l2)
    else:
        res = l2
        l2 = l2.next
        res.next = self.mergeTwoLists(l1,l2)
    return res

def mergeKLists(self, lists: List[ListNode]) -> ListNode:
    if not lists: return None
    if len(lists) ==1 : return lists[0]
    if len(lists) ==2 : return self.mergeTwoLists(lists[0],lists[1])
    return self.mergeTwoLists(self.mergeKLists(lists[:len(lists)//2]),self.mergeKLists(lists[len(lists)//2:]))