问题
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
解决:
思想:
- 这道题可以使用递归实现,新链表也不需要构造新节点,我们下面列举递归三个要素
- 终止条件:两条链表分别名为 l1 和 l2,当 l1 为空或 l2 为空时结束
- 返回值:每一层调用都返回排序好的链表头
- 本级递归内容:如果 l1 的 val 值更小,则将 l1.next 与排序好的链表头相接,l2 同理
- O(m+n)O(m+n),mm 为 l1的长度,nn 为 l2 的长度
python代码:
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if(l1==None):
return l2
if(l2==None):
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
执行用时 :56 ms, 在所有 Python3 提交中击败了89.24%的用户
内存消耗 :13.1 MB, 在所有 Python3 提交中击败了76.59%的用户
c++代码:
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
if(l1->val<l2->val)
{
l1->next=mergeTwoLists(l1->next,l2);
return l1;
}
else
{
l2->next=mergeTwoLists(l1,l2->next);
return l2;
}
}
};
执行结果:
通过显示详情执行用时 :12 ms, 在所有 C++ 提交中击败了93.52%的用户
内存消耗 :9 MB, 在所有 C++ 提交中击败了77.74%的用户

160

被折叠的 条评论
为什么被折叠?



