美文网首页
Leetcode —— Easy 21 Merge Two S

Leetcode —— Easy 21 Merge Two S

作者: 纳萨立克 | 来源:发表于2019-03-18 16:39 被阅读0次

    题目: 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->val<l2->val)
        {
            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 S

          本文链接:https://www.haomeiwen.com/subject/gdrbmqtx.html