本文共 794 字,大约阅读时间需要 2 分钟。
要合并两个升序链表为一个新的升序链表,可以使用递归的方法。递归函数比较当前两个链表的头节点,选择较小的节点作为结果的下一个节点,并继续递归合并剩下的链表。这样可以确保合并后的链表仍然保持升序。
class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if l1 is None: return l2 elif l2 is None: return l1 elif l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2
这种方法的时间复杂度为O(n + m),其中n和m分别是两个链表的长度,确保合并后的链表仍然是升序排列的。
转载地址:http://qeuwk.baihongyu.com/