21. 合并两个有序链表

力扣原题链接(点我直达)

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

示例:

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

第一版,熟悉一下怎么写的再说

执行用时 :12 ms, 在所有 cpp 提交中击败了77.75%的用户

内存消耗 :9 MB, 在所有 cpp 提交中击败了76.64%的用户

struct ListNode {

    int val;
    ListNode* next;
    ListNode(int x) :val(x), next(nullptr) {}
};

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    if (l1 == nullptr) return l2;
    if (l2 == nullptr)  return l1;

    ListNode* res=nullptr;

    if (l1->val <= l2->val) {

        res = l1;
        l1 = l1->next;

    }
    else {

        res = l2;
        l2 = l2->next;
    }

    ListNode* head = res;

    while (l1 && l2) {
        if (l1->val <= l2->val) {

            res->next = l1;     
            l1 = l1->next;
            res = res->next;

        } else {
            res->next = l2;
            l2 = l2->next;
            res = res->next;
        }

    }

    res->next = l1 == nullptr ? l2 : l1;
    return head;
}