leetcode编程题:合并两个有序链表

难度:简单

输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。

示例1:

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

0 <= 链表长度 <= 1000

题解如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
    struct ListNode *pre = (struct ListNode *)malloc(sizeof(struct ListNode));  //一定要用malloc分配一块链表指针内存
    struct ListNode *end = pre;
    pre = end;

    while (l1 != NULL && l2 != NULL) {
        if ((l1->val) >= (l2->val)) {
            end->next = l2;
            end = l2;
            l2 = l2->next;    
        } else {
            end->next = l1;
            end = l1;
            l1 = l1->next;
        }
    }
    end->next = l1 != NULL ? l1 : l2;
    return pre->next;
}

你可能感兴趣的:(数据结构与算法,C/C++,objective-c,链表)