欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 幼教 > leetcode21. Merge Two Sorted Lists

leetcode21. Merge Two Sorted Lists

2025/5/2 2:53:05 来源:https://blog.csdn.net/weixin_44245188/article/details/143667061  浏览:    关键词:leetcode21. Merge Two Sorted Lists

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]

思路:递归

class Solution:def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:if not l1: return l2  # 终止条件,直到两个链表都空if not l2: return l1if l1.val <= l2.val:  # 递归调用l1.next = self.mergeTwoLists(l1.next,l2)return l1else:l2.next = self.mergeTwoLists(l1,l2.next)return l2

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词