23. Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
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):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
if not lists:
return None
start = 0
end = len(lists) - 1
while start != end or end != 0:
if start >= end:
start = 0
else:
lists[start] = self.mergeTwoLists(lists[start], lists[end])
start += 1
end -= 1
return lists[0]
def mergeTwoLists(self, l1, l2): # 将两个lists按顺序合并
current = head = ListNode(0)
while l1 and l2:
if l1.val <= l2.val:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current = current.next
current.next = l1 or l2
return head.next