LeetCode 21--合并两个有序链表 ( Merge Two Sorted Lists ) ( C语言版 )

题目描述 : 

方法一 : 递归合并

代码如下 : 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* newNode;
    if(!l1)
        return l2;
    if(!l2)
        return l1;
    if(l1->val<l2->val)
    {
        newNode=l1;
        newNode->next=mergeTwoLists(l1->next,l2);
    }
    else
    {
        newNode=l2;
        newNode->next=mergeTwoLists(l1,l2->next);
    }
    return newNode;
}

方法二 : 非递归合并

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* newNode;
    struct ListNode* tail;
    if(!l1)
        return l2;
    else if(!l2)
        return l1;
    else{
        if(l1->val<l2->val){
            newNode=l1;
            l1=l1->next;
        }
        else{
            newNode=l2;
            l2=l2->next;
        }
        tail=newNode;
        while(l1&&l2){
            if(l1->val<l2->val){
                tail->next=l1;
                l1=l1->next;
            }
            else{
                tail->next=l2;
                l2=l2->next;
              
            }  
            tail=tail->next;
        }
        if(l1||l2)
            tail->next=l1!=NULL?l1:l2;
    }
    return newNode;
}

 

展开阅读全文

没有更多推荐了,返回首页