Merge two Sorted Lists的进阶版
建立Merge two Sorted Lists函数 合并两个链表,mergeKLists中不断二分再合并
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if not lists:
return None
if len(lists) == 1:
return lists[0]
l1 = self.mergeKLists(lists[:len(lists)//2])
l2 = self.mergeKLists(lists[len(lists)//2:])
head = self.mergeTwoLists(l1,l2)
return head
def mergeTwoLists(self, l1, l2):
if not l1 and not l2:
return None
if not l1:
return l2
if not l2:
return l1
p = ListNode(0)
res = p
while l1 and l2:
if l1.val < l2.val:
p.next = l1
l1=l1.next
p = p.next
else:
p.next = l2
l2 = l2.next
p = p.next
if l1:
p.next=l1
if l2:
p.next=l2
return res.next