【C语言刷LeetCode】21. 合并两个有序链表(E)

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

示例:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

还是属于双指针问题。其中int最大值为0x7fffffff,而不是 0xffffffff,也不是0xfffffffe.

int getval(struct ListNode* list) {
    if (list) {
        return list->val;
    } else {
        return 0x7fffffff;
    }
}

struct ListNode *head;
struct ListNode *end;

void addinl3(int val) {
    struct ListNode *pnew = (struct ListNode *)malloc(sizeof(struct ListNode));
    
    pnew->val = val;
    pnew->next = NULL;
    
    if (head) {
        end->next = pnew;
    } else {
        head = pnew;
    }
    
    end = pnew;
}

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
    int val1,val2,val;;
    head = NULL;
    end = NULL;

    if (l1 == NULL) {
        return l2;
    }
    
    if (l2 == NULL) {
        return l1;
    }
    
    if ((l1 == NULL) && (l2 == NULL)) {
        return 0;
    }
    
    while(l1 || l2) {
        
        val1 = getval(l1);
        val2 = getval(l2);
        //printf("val1=%d,val2=%d\n",val1,val2);
        if (val1 < val2) {
            l1 = l1->next;
            val = val1;
        } else {
            l2 = l2->next;
            val = val2;
        }
        
        addinl3(val);
    }

    return head; 
}
发布了102 篇原创文章 · 获赞 17 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/jin615567975/article/details/104290529