用 Python 合併兩個已排序列表


假設我們有兩個已排序列表 A 和 B。我們必須合併它們並只生成一個已排序列表 C。列表的大小可能不同。

例如,假設 A = [1,2,4,7] 且 B = [1,3,4,5,6,8],則合併後的列表 C 為 [1,1,2,3,4,4,5,6,7,8]

我們使用遞迴解決這個問題。所以函式將如下工作 -

  • 假設 merge() 函式的列表 A 和 B
  • 如果 A 為空,則返回 B,如果 B 為空,則返回 A
  • 如果 A 中的值 <= B 中的值,則 A.next = merge(A.next, B) 並返回 A
  • 否則,則 B.next = merge(A, B.next) 並返回 B

讓我們看看實現以更好地理解

示例(Python)

 即時演示

class ListNode:
   def __init__(self, data, next = None):
      self.val = data
      self.next = next
   def make_list(elements):
      head = ListNode(elements[0])
      for element in elements[1:]:
         ptr = head
         while ptr.next:
            ptr = ptr.next
         ptr.next = ListNode(element)
      return head
def print_list(head):
   ptr = head
   print('[', end = "")
   while ptr:
      print(ptr.val, end = ", ")
      ptr = ptr.next
   print(']')
class Solution:
   def mergeTwoLists(self, l1, l2):
      """
      :type l1: ListNode
      :type l2: ListNode
      :rtype: ListNode
      """
      if not l1:
         return l2
      if not l2:
         return l1
      if(l1.val<=l2.val):
         l1.next = self.mergeTwoLists(l1.next,l2)
         return l1
      else:
         l2.next = self.mergeTwoLists(l1,l2.next)
         return l2
head1 = make_list([1,2,4,7])
head2 = make_list([1,3,4,5,6,8])
ob1 = Solution()
head3 = ob1.mergeTwoLists(head1,head2)
print_list(head3)

輸入

head1 = make_list([1,2,4,7])
head2 = make_list([1,3,4,5,6,8])

輸出

[1, 1, 2, 3, 4, 4, 5, 6, 7, 8, ]

更新於: 28-Apr-2020

1 千多次瀏覽

開啟您的職業

完成課程獲得認證

開始
廣告
© . All rights reserved.