1、迭代法
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode *head1=l1,*head2=l2,*pre;
struct ListNode *first = (struct ListNode*)malloc(sizeof(struct ListNode));
first->next = NULL;
pre = first;
while(head1!=NULL && head2!=NULL){
if(head1->val <= head2->val){
pre->next = head1;
head1 = head1->next;
}
else{
pre->next = head2;
head2 = head2->next;
}
pre = pre->next;
}
if(head1 != NULL)
pre->next = head1;
else if(head2 != NULL)
pre->next = head2;
return first->next;
}
2、递归法
struct ListNode* mergeTwoLists(struct ListNode* l1, struct 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;
}