1、Description
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
(来源于Leecode)
2、Example
输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6
3、Code
# 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):
if len(lists)==0:
return None
if len(lists)==1:
return lists[0]
newlists = []
if len(lists)%2==1:
for li in range(0,len(lists)-1,2):
newlists.append(self.merge2Lists(lists[li],lists[li+1]))
newlists.append(lists[len(lists)-1])
else:
for li in range(0,len(lists),2):
newlists.append(self.merge2Lists(lists[li],lists[li+1]))
return self.mergeKLists(newlists)
def merge2Lists(self, l1, l2):
head = point = ListNode(0)
while l1 and l2:
if l1.val<=l2.val:
point.next = l1
l1=l1.next
else:
point.next = l2
l2=l2.next
point = point.next
if not l1:
point.next = l2
else :
point.next = l1
return head.next
4、Result