递归实现
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
if(l1->val < l2->val){
l1->next = mergeTwoLists(l1->next,l2);
return l1;
}else{
l2->next = mergeTwoLists(l1,l2->next);
return l2;
}
}
};
常规实现
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* q=new ListNode;
ListNode* p=q;
while(l1!=NULL&&l2!=NULL){
if(l1->val<l2->val)p->next=l1,l1=l1->next;
else p->next=l2,l2=l2->next;
p=p->next;
}
if(l1==NULL)p->next=l2;
else if(l2==NULL)p->next=l1;
ListNode* res= q->next;
delete q;
return res;
}
};
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
struct ListNode* p = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* ret = NULL;
struct ListNode* p1 = l1;
struct ListNode* p2 = l2;
if (p1 && p2) {
if (p1->val <= p2->val) {
p = p1;
p1 = p1->next;
} else {
p = p2;
p2 = p2->next;
}
ret = p;
} else if (p2 == NULL) {
return p1;
} else if (p1 == NULL) {
return p2;
}
while(p1 && p2) {
if (p1->val <= p2->val) {
p->next = p1;
p = p1;
p1 = p1->next;
} else {
p->next = p2;
p = p2;
p2 = p2->next;
}
}
p->next = p1 ? p1 : p2;
return ret;
}
};