[Python-leetcode23-multi-way merge] merge k sorted linked list

Combine the k sorted linked lists and return the merged sorted linked list. Please analyze and describe the complexity of the algorithm.

Example:

Input:
[
  1-> 4-> 5,
  1-> 3-> 4,
  2-> 6
]
Output: 1-> 1-> 2-> 3-> 4-> 4-> 5-> 6

 

Idea: merge two by two at a time, and then add the merged result back to the list until only one linked list remains.

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

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        while len(lists)>1:
            a=lists.pop() if len(lists)>0 else None
            b=lists.pop() if len(lists)>0 else None
            lists.insert(0,self.mergeTwoLists(a,b))
        return None if len(lists)<1 else lists[0]
    def mergeTwoLists(self,l1,l2):
        newHead=ListNode(0)
        t=newHead
        while l1 and l2:
            if l1.val<=l2.val:
                t.next=ListNode(l1.val)
                l1=l1.next
            else:
                t.next=ListNode(l2.val)
                l2=l2.next
            t=t.next
        if l1:
            t.next=l1
        if l2:
            t.next=l2
        return newHead.next

 

Guess you like

Origin www.cnblogs.com/xiximayou/p/12731001.html