ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == NULL){
if(l2 == NULL){
return NULL;
}else{
return l2;
}
}
if(l1 != NULL && l2 == NULL){
return l1;
}
ListNode* head=NULL;
ListNode* ans=head;
while(l1!=NULL&&l2!=NULL){
ListNode* curr=NULL;
if(l1->val < l2->val){
curr=new ListNode(l1->val);
l1=l1->next;
}else{
curr=new ListNode(l2->val);
l2=l2->next;
}
if(head == NULL){
head=curr;
ans=head;
}else{
head->next=curr;
head=head->next;
}
}
while(l1!=NULL){
ListNode* curr=new ListNode(l1->val);
head->next=curr;
head=head->next;
l1=l1->next;
}
while(l2!=NULL){
ListNode* curr=new ListNode(l2->val);
head->next=curr;
head=head->next;
l2=l2->next;
}
return ans;
}