LeetCoed Day19 merge-two-sorted-lists

法一:使用一个额外的链表

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode *head=new ListNode(-1);//注意要初始化
        ListNode *p=head;
        while(l1&&l2){
            if(l1->val<l2->val){
                p->next=l1;
                l1=l1->next;
            }
            else{
                p->next=l2;
                l2=l2->next;
            }
            p=p->next;
        }
        p->next=l1?l1:l2;
        return head->next;
    }
};

法二:不使用额外链表,递归

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(!l1) return l2;
        if(!l2) 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) {
        if(!l1) return l2;
        if(!l2) return l1;
        ListNode *head=l1->val<l2->val?l1:l2;
        ListNode *p=l1->val<l2->val?l2:l1;//一个做head,另一个记为p
        head->next=mergeTwoLists(head->next,p);
        return head;
    }
};
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(!l1||(l2 && l1->val>l2->val )) swap(l1,l2);//默认选l1为头,若l1为空或者l2的首位小于l1,则交换l1,l2,将l2换到l1做头。
        if(l1) l1->next=mergeTwoLists(l1->next,l2);
        return l1;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41394379/article/details/83181672
今日推荐