LeetCode#21 合并两个有序链表
题目描述
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
代码实现
// 时间复杂度为O(m+n) 空间复杂度O(m+n)
void addNode(struct ListNode *node, int val)
{
struct ListNode *l = (struct ListNode *)malloc(sizeof(struct ListNode));
l->val = val;
l->next = node->next;
node->next = l;
}
struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2)
{
if (l1 == NULL && l2 == NULL)
return NULL;
if (l1 == NULL)
return l2;
if (l2 == NULL)
return l1;
struct ListNode *newlist = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode *head = newlist;
head->next = NULL;
while (l1 && l2)
{
if (l1->val <= l2->val)
{
addNode(newlist, l1->val);
newlist = newlist->next;
l1 = l1->next;
}
else
{
addNode(newlist, l2->val);
newlist = newlist->next;
l2 = l2->next;
}
}
if (l1 != NULL)
{
newlist->next = l1;
}
if (l2 != NULL)
{
newlist->next = l2;
}
return head->next;
}
// 暴力解法,空间复杂度优化,即返回原链表 注意哑结点的使用
void addNode(struct ListNode *node, int val)
{
struct ListNode *l = (struct ListNode *)malloc(sizeof(struct ListNode));
l->val = val;
l->next = node->next;
node->next = l;
}
struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2)
{
if (l1 == NULL && l2 == NULL)
return NULL;
if (l1 == NULL)
return l2;
if (l2 == NULL)
return l1;
struct ListNode *dummy = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode *prev = dummy;
dummy->next = NULL;
while (l1 && l2)
{
if (l1->val <= l2->val)
{
prev->next = l1;
l1 = l1->next;
}
else
{
prev->next = l2;
l2 = l2->next;
}
prev = prev->next;
}
if (l1 != NULL)
{
prev->next = l1;
}
if (l2 != NULL)
{
prev->next = l2;
}
return dummy->next;
}
// 合并(l1 L2)等价于L1->next = 合并(L1->next,L2)
// 子问题与原问题具有相同结构,考虑递归
// 就是将两个链表中对应的值比较,最终结果是两者中较小的值与其余值合并后的结果,这就构成了递归
// 时间复杂度O(M+N) 空间复杂度O(M+N)
class Solution
{
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
if (l1 == nullptr)
{
return l2;
}
else if (l2 == nullptr)
{
return l1;
}
else if (l1->val < l2->val)
{
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
else
{
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};