LeetCode-将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 示例: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4

---恢复内容开始---

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
    
    if (l1 == NULL && l2 == NULL) return NULL;
    struct ListNode *ret = (struct ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode *cur = ret;
    while(l1 || l2)
    {
        struct ListNode *tmp = (struct ListNode *)malloc(sizeof(struct ListNode));   
        if (l1 && l2)
        {
            if (l1->val > l2->val)
            {
                tmp->val = l2->val;
                l2 = l2->next;
            }
            else
            {
                tmp->val = l1->val;
                l1 = l1->next;
            }
        }
        else if(l1 == NULL)
        {
            tmp->val = l2->val;
            l2 = l2->next;
        }
        else
        {
            tmp->val = l1->val;
            l1 = l1->next;
        }
        cur->next = tmp;
        cur = cur->next;                   
    }
    return ret->next;
}

  

输入
[]
[0]
输出
[0,0]
预期结果
[0]

---恢复内容结束---

posted @ 2018-11-29 21:36  xinfenglee  阅读(186)  评论(0编辑  收藏  举报