class Solution
{
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
if (l1 == NULL)
{
return l2;
}
if (l2 == NULL)
{
return l1;
}
ListNode* help = new ListNode(0);
ListNode* head = help;
while (l1 && l2)
{
if (l1->val > l2->val)
{
help->next = l2;
l2 = l2->next;
}
else
{
help->next = l1;
l1 = l1->next;
}
help = help->next;
}
if (l1)
{
help->next = l1;
}
if (l2)
{
help->next = l2;
}
return head->next;
}
};
网上的用递归的解法:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
ListNode *ret = NULL;
if (l1->val < l2->val)
{
ret = l1;
ret->next = mergeTwoLists(l1->next, l2);
}
else
{
ret = l2;
ret->next = mergeTwoLists(l1, l2->next);
}
return ret;
}