# leetcode--21 合并两个有序链表

```输入：1->2->4, 1->3->4

//合并两个有序链表
{
{
return nullptr;
}

{
}

{
}

ListNode* root = new ListNode('#');
ListNode* p = root;
while (currentA != nullptr)
{
if (currentA != nullptr && currentB != nullptr)
{
if (currentA->data > currentB->data)
{
p->next = currentB;
currentB = currentB->next;
}
else
{
p->next = currentA;
currentA = currentA->next;
}
p = p->next;
}

if (currentB == nullptr &&currentA != nullptr)
{
p->next = currentA;
break;
}

}

if (currentA == nullptr &&currentB!=nullptr)
{
p->next = currentB;
}

currentA = root->next;
delete root;
root = nullptr;
return currentA;
}

//优化

{
{
}

{
}

ListNode* root = new ListNode('#');
ListNode* p = root;
while (currentA != nullptr)
{
if (currentA != nullptr && currentB != nullptr)
{
if (currentA->data > currentB->data)
{
p->next = currentB;
currentB = currentB->next;
}
else
{
p->next = currentA;
currentA = currentA->next;
}
p = p->next;
}

if (currentB == nullptr &&currentA != nullptr)
{
p->next = currentA;
break;
}

}

if (currentA == nullptr &&currentB!=nullptr)
{
p->next = currentB;
}

currentA = root->next;
delete root;
root = nullptr;
return currentA;
}

;