在 Python 中合并两个排序列表

pythonserver side programmingprogramming更新于 2025/10/31 16:44:17

假设我们有两个排序列表 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, ]

相关文章


有用资源