Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Tag:两路归并
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL){}
};
ListNode * mergeTwoLists(ListNode *l1, ListNode *l2)
{
ListNode * head = NULL;
ListNode * p = head;
while(l1 != NULL || l2 != NULL)
{
int val = 0;
if(l1 == NULL)
{
val = l2->val;
l2 = l2->next;
}
else if(l2 == NULL)
{
val = l1->val;
l1 = l1->next;
}
else
{
if(l1->val <= l2->val)
{
val = l1->val;
l1 = l1->next;
}
else
{
val = l2->val;
l2 = l2->next;
}
}
ListNode * tmp = new ListNode(val);
if(head == NULL)
{
head = p = tmp;
}
else
{
p->next = tmp;
p = p->next;
}
}
return head;
}