合併n個已排序的鏈表

合併n個已排序的鏈表

Merge k Sorted Lists

  • 合併n個已排序的鏈表,新鏈表中的每一個節點必須是來自輸入的原鏈表的節點(即不能構造新的節點),返回新鏈表的頭部。git

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

example 1算法

input:
[
  3->5->8,
  2->11>12,
  4->8,
]
output:
2->3->4->5->8->8->11->12

思路

  1. 參照本人以前已發表的《合併兩個已排序的鏈表》,只須要將此算法應用n-1次便可獲得新鏈表。segmentfault

代碼

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

    def __cmp__(self, other):
        return self.val <= other




class Solution(object):

    def mergeKLists_new(self, links):
        """
        :type links: List[ListNode]
        :rtype: ListNode
        """
        head = None
        for i in links:
            head = self.mergeTwoLists(head, i)
        return head


    # 爲了方便閱讀,給出以前的代碼
    # from mergeTwoLists,《合併兩個已排序鏈表》的代碼
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if None in (l1, l2):
            return l1 or l2
        head = tail = l1 if l1.val <= l2.val else l2
        a = l1 if l1.val > l2.val else l1.next
        b = l2 if l1.val <= l2.val else l2.next
        while a and b:
            if a.val <= b.val:
                tail.next = a
                tail, a = tail.next, a.next
            else:
                tail.next = b
                tail, b = tail.next, b.next
        tail.next = a or b
        return head

本題以及其它leetcode題目代碼github地址: github地址code

相關文章
相關標籤/搜索