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.
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode *head=NULL,*pre=NULL,*plist01=l1,*plist02=l2;
if((plist01!=NULL)&&(plist02!=NULL)&&(plist01->val<plist02->val)){
head=plist01;
pre=plist01;
plist01=plist01->next;
}
else if((plist01!=NULL)&&(plist02!=NULL))
{
head=plist02;
pre=plist02;
plist02=plist02->next;
}
while (plist01&&plist02)
{
if(plist01->val<plist02->val){
pre->next=plist01;
pre=plist01;
plist01=plist01->next;
}else
{
pre->next=plist02;
pre=plist02;
plist02=plist02->next;
}
}
if(pre==NULL){
head=((plist01==NULL)?plist02:plist01);
}else
{
pre->next=((plist01==NULL)?plist02:plist01);
}
return head;
}