题目:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

题解思路:
方法一:递归
函数代码一:
l1结点和l2结点比较值大小关系,谁小则是合并链表的头结点,并且返回头结点。
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(!l1)
{
return l2;
}
else if(!l2)
{
return l1;
}
if(l1->val<l2->val)
{
l1->next=mergeTwoLists(l1->next,l2);
return l1;
}
else
{
l2->next=mergeTwoLists(l1,l2->next);
return l2;
}
}
};
函数代码一:解法二
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(!l1)
{
return l2;
}
else if(!l2)
{
return l1;
}
if(l1->val<l2->val)
{
l1->next=mergeTwoLists(l1->next,l2);
return l1;
}
else
{
l2->next=mergeTwoLists(l2->next,l1);
return l2;
}
}
};
函数代码二:
引入了p结点作为合并链表的头结点,最后返回p结点。
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *p=NULL;
if(!l1)
{
return l2;
}
else if(!l2)
{
return l1;
}
if(l1->val<l2->val)
{
p=l1;
p->next=mergeTwoLists(l1->next,l2);
}
else
{
p=l2;
p->next=mergeTwoLists(l1,l2->next);
}
return p;
}
};
方法二:迭代+引入头结点dummy
函数代码:
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode dummy(0);
ListNode *p=&dummy;
while(l1&&l2)
{
if(l1->val<=l2->val)
{
p->next=l1;
l1=l1->next;
}
else
{
p->next=l2;
l2=l2->next;
}
p=p->next;
}
if(l1)
{
p->next=l1;
}
else if(l2)
{
p->next=l2;
}
return dummy.next;
}
};

本文介绍了一种将两个升序链表合并为一个新升序链表的算法,提供了递归和迭代两种实现方法。递归方法通过比较两链表节点值,确定合并链表头结点;迭代方法引入虚拟头结点,简化边界条件处理。
553

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



