合并多个有序链表

Python解决方案1:

# 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
        """
        all_list = []
        for i in lists:
            all_list += self.tolist(i)
        all_list.sort()
        if not all_list:
            return None
        head = ListNode(all_list[0])
        out = head
        for i in all_list[1:]:
            head.next = ListNode(i)
            head = head.next
        return out
        
    def tolist(self,head):
        out = []
        while head:
            out.append(head.val)
            head = head.next
        return out

Python解决方案2:

# 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
        """
    
        length = len(lists)
        if length == 0:
            return None
        else:
            while len(lists) > 1:
                lists.append(self.mergeTwoLists(lists.pop(0),lists.pop(0)))
            return lists[0]
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        prev = ListNode(0)
        head = prev
        while l1 and l2:
            if l1.val <= l2.val:
                prev.next = l1
                l1 = l1.next
            else:
                prev.next = l2
                l2 = l2.next
            prev = prev.next
        if l1:
            prev.next = l1
        if l2:
            prev.next = l2  
        return head.next

猜你喜欢

转载自www.cnblogs.com/wenqinchao/p/10620450.html