# Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None


# Actually this one is not hard. Merge k lists recursively by dividing the whole array of lists by half.
# If each linked list has max length of N, then according to the master theorem, the running time
# complexity is O(Nklogk). The space complexity is O(logk) since each recursive call generate some constant
# size varaiables.
class Solution:
    # @param a list of ListNode
    # @return a ListNode
    def mergeKLists(self, lists):
        M = len(lists)
        if M==0:
            return None
        if M == 1:
            return lists[0]
        left_lists = self.mergeKLists(lists[:M/2])
        right_lists = self.mergeKLists(lists[M/2:])
        return self.merge2lists(left_lists, right_lists)

    def merge2lists(self, l1, l2):
        if l1 == None:
            return l2
        h0 = ListNode(0)
        h0.next = l1
        prev_node = h0
        while l1!=None and l2!=None:
            if l1.val > l2.val:
                prev_node.next = l2
                l2_next = l2.next
                l2.next = l1
                l2 = l2_next
            else:
                l1 = l1.next
            prev_node = prev_node.next
        if l2 != None:
            prev_node.next = l2
        return h0.next

