LeetCode -- 21. Merge Two Sorted Lists

My solution:

    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode *retList = NULL, *tempList = NULL;
        if(!l1 && !l2) return retList;
        int val = 0, val1 = 0, val2 = 0;
        retList = tempList = new ListNode(0);
        while(l1 || l2){
            val1 = l1?l1->val:0;
            val2 = l2?l2->val:0;
            if(((val1<val2) && l1) || !l2){
                tempList->val = val1;
                if(!(l1->next) && !l2) return retList;
                tempList->next = new ListNode(0);
                tempList = tempList->next;
                l1 = (l1->next)?l1->next:NULL;
                continue;
            }
            else{
                tempList->val = val2;
                if(!(l2->next) && !l1) return retList;
                
                tempList->next = new ListNode(0);
                tempList = tempList->next;
                l2 = (l2->next)?l2->next:NULL;
                continue;      
            }
        }
        return retList;
   }

 Other Guy's solution:

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) 
{
    if(!l1)         // If no l1, return l2
        return l2;
    if(!l2)         // If no l2, return l1
        return l1;
    if(!l2 && !l1)  // If neither, return NULL;
        return NULL;
        
    ListNode* head; // The pointer we will use to construct a merged list
    
    
    if(l1->val < l2->val)   // If l1 less than l2
    {
        head = l1;          // We start at l1
        l1 = l1->next;      // and iterate l1
    }
    else                    // If l2 less than l1
    {
        head = l2;          // We start at l2
        l2 = l2->next;      // and iterate l2
    }
    
    ListNode* ret = head;   // We need to save the addres of the head of the list
    
    while(l1 && l2)         // While both input lists have values
    {
        if(l1->val < l2->val)   // Compare the current values, if l1 is less
        {
            head->next = l1;    // Append the merged list with l1's current address
            l1 = l1->next;      // Advance l1
        }
        else                    // Else, l2 had the low value
        {
            head->next = l2;    // Append l2 to the list
            l2 = l2->next;      // Advance l2
        }
        head->next->next = NULL;    // Append a NULL teminator to the list
        head = head->next;          // Advance the merged list
    }
    
    // Lastly, if list were different lengths, we need to append the longer list tail to the merged list
    
    if(l1)
        head->next = l1;
    else if(l2)
        head->next = l2;
        
    return ret; // Return the starting address of head that we saved.
}

  

转载于:https://www.cnblogs.com/feliz/p/10909932.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值