一、题目
Merge two sorted linked lists and return itas a new list. The new list should be made by splicing together the nodes ofthe first two lists.
二、代码
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* head=new ListNode(0);
ListNode*p=head;
while(l1!=NULL || l2!=NULL)
{
if(l1==NULL)
{
p->next=l2;
l2=l2->next;
}
elseif (l2==NULL)
{
p->next=l1;
l1=l1->next;
}
else
{
if(l1->val < l2->val)
{
p->next=l1;
l1=l1->next;
}
else
{
p->next=l2;
l2=l2->next;
}
}
p=p->next;
}
returnhead->next;
}
};
三、思路
两个链表两个指针的val比对将新链表指针指向较小的节点。