题目:
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.
Subscribe to see which companies asked this question
Solution:
很简单,代码如下:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
ListNode * t1 = l1;
ListNode * t2 = l2;
ListNode * l3 = new ListNode(NULL);
ListNode *head = l3;
while(t1!=NULL && t2!=NULL)
{
if(t1->val < t2->val)
{
l3->val = t1->val;
t1 = t1->next;
}
else
{
l3->val = t2->val;
t2 = t2->next;
}
if(t1 != NULL && t2 !=NULL)
{
l3->next = new ListNode(NULL);
l3 = l3->next;
}
}
while(t1!=NULL)
{
l3->next = new ListNode(NULL);
l3 = l3->next;
l3->val = t1->val;
t1 = t1->next;
}
while(t2!=NULL)
{
l3->next = new ListNode(NULL);
l3 = l3->next;
l3->val = t2->val;
t2 = t2->next;
}
return head;
}