天天看點

LeetCode 21. Merge Two Sorted Lists(合并兩個有序連結清單) -- c語言21. Merge Two Sorted Lists

21. Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
           

解題思路:

/*
執行用時 : 8 ms, 在Merge Two Sorted Lists的C送出中擊敗了97.49% 的使用者
記憶體消耗 : 7.2 MB, 在Merge Two Sorted Lists的C送出中擊敗了93.61% 的使用者
*/
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
    //考慮特殊情況
    if(l1 == NULL) return l2;
    if(l2 == NULL) return l1;
    
    //定義傳回結果連結清單,并配置設定空間
    struct ListNode *result = (struct ListNode*)malloc(sizeof(struct ListNode));
    //始終指向結果連結清單尾,進行插入操作
    struct ListNode *temp = result;
    
    //開始插入
    while(l1&&l2){
        if(l1->val <= l2->val)
        {
            temp->next = l1;
            l1 = l1->next;
        }
        else 
        {
            temp->next = l2;
            l2 = l2->next;
            
        }
        //指向結果連結清單尾
        temp = temp->next;
    }
    //還有連結清單沒有合并,連結到結果連結清單尾
    temp->next = (l1 != NULL)?l1:l2;
    
    return result->next;
    free(result);
    
}
           
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;
    }
    
}
           

後記:

試想一下對于無序連結清單該如何處理。

繼續閱讀