题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
if (l1 == nullptr)return l2;
if (l2 == nullptr)return l1;
ListNode* head = new ListNode(-1);
ListNode* root = head;
while (l1 && l2)
{
if (l1->val < l2->val)
{
head->next = l1;
head = head->next;
l1 = l1->next;
}
else
{
head->next = l2;
head = head->next;
l2 = l2->next;
}
}
if (l1)head->next = l1;
if (l2)head->next = l2;
return root->next;
}
递归:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
if (l1 == nullptr)return l2;
if (l2 == nullptr)return l1;
ListNode* p = NULL;
if (l1->val < l2->val)
{
p = l1;
p->next = mergeTwoLists(l1->next, l2);
}
else
{
p = l2;
p->next = mergeTwoLists(l2->next, l1);
}
return p;
}