Leetcode —— Easy 21 Merge Two Sorted Lists

题目: Merge two sorted linked lists and return it as a new list. The new list

方法一 : 递归函数

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* header;
    if(!l1)
        return l2;
    if(!l2)
        return l1;
    if(l1->valval)
    {
        header =l1;
        header->next=mergeTwoLists(l1->next,l2);
    }
    else
    {
        header =l2;
        header->next=mergeTwoLists(l1,l2->next);
    }
    return header;
}

方法二

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

    if(!l1){
        head->next = l2;
    }

    if(!l2){
        head->next = l1;
    }
    
    return ret;
}

你可能感兴趣的:(Leetcode —— Easy 21 Merge Two Sorted Lists)