Merge Two Sorted Lists
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.
class Solution
{
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
if(!l1 && !l2)
return NULL;
else if(!l1)
return l2;
else if(!l2)
return l1;
ListNode * head = NULL;
ListNode * temp;
if(l1->val >= l2->val)
{
head = l2;
head->next = mergeTwoLists(l1, l2->next);
}
else
{
head = l1;
head->next = mergeTwoLists(l1->next, l2);
}
return head;
}
};
下面采用循环来解决这个问题
class Solution
{
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
{
if(!l1 && !l2)
return NULL;
else if(!l1)
return l2;
else if(!l2)
return l1;
ListNode * head = NULL;
ListNode * p1 = l1;
ListNode * p2 = l2;
if(p1->val >= p2->val)
{
head = p2;
p2 = p2->next;
}
else
{
head = p1;
p1 = p1->next;
}
ListNode * p = head;
while(p1 || p2)
{
if(!p1 || (p2 && p1->val >= p2->val ))
{
p->next = p2;
p2 = p2->next;
}
else
{
p->next = p1;
p1 = p1->next;
}
p = p->next;
}
return head;
}
};