初级算法_字符串_合并两个有序链表

题目描述

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:

输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4

解题思路

稍简单,不影响打dota暴走,咱们就过了。

代码

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode *pstHead;
    struct ListNode *pstTmp;

    if (0 == l1)
    {
        return l2;
    }
    if (0 == l2)
    {
        return l1;
    }
    
    if (l1->val > l2->val)
    {
        pstHead = l2;
        l2 = l2->next;
    }
    else
    {
        pstHead = l1;
        l1 = l1->next;
    }
    pstTmp = pstHead;

    while (0 != l1 && 0 != l2)
    {
        if (l1->val > l2->val)
        {
            pstTmp->next = l2;
            l2 = l2->next;
        }
        else
        {
            pstTmp->next = l1;
            l1 = l1->next;
        }
        pstTmp = pstTmp->next; 
    }
    if (0 == l1)
    {
        pstTmp->next = l2;
    }
    if (0 == l2)
    {
        pstTmp->next = l1;
    }


    return pstHead;
}

看答案

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
    if(l1 == NULL)
        return l2;
    if(l2 == NULL)
        return l1;
    
    struct ListNode *head,*cur1,*cur2,*pre,*next;
    if(l1->val < l2->val) {
        head = l1; 
    } else {
        head = l2;
    }
        
    if(l1->val < l2->val) {
        cur1 = l1; 
        cur2 = l2;
    } else {
        cur1 = l2;
        cur2 = l1;
    }
    
    while(cur1 != NULL && cur2 != NULL){
        if(cur1->val <= cur2->val){
            pre = cur1;
            cur1 = cur1->next;
        }else{
            next = cur2->next;
            pre->next = cur2;
            cur2->next = cur1;
            pre = cur2;
            cur2 = next;
        }
    }
    
    if(cur1 == NULL) {
        pre -> next = cur2;
    } else {
        pre -> next = cur1;
    }

    return head;
}

总结

没有总结。

你可能感兴趣的:(leetcode)