天天看点

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;
    }
    
}
           

后记:

试想一下对于无序链表该如何处理。

继续阅读