Skip to content

Latest commit

 

History

History
31 lines (30 loc) · 743 Bytes

21.md

File metadata and controls

31 lines (30 loc) · 743 Bytes

#21. Merge Two Sorted Lists 题目链接

直接合并

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
    if (l1 == NULL || l2 == NULL)
    {
        return l1 == NULL?l2:l1;
    }
    bool l1Small = l1->val < l2->val;
    struct ListNode *head = l1Small?l1:l2;
    if (l1Small)
        l1 = l1->next;
    else
        l2 = l2->next;
    struct ListNode *l3 = head;
    while (l1 != NULL && l2 != NULL)
    {
        l1Small = l1->val < l2->val;
        l3 ->next = l1Small?l1:l2;
        if (l1Small)
            l1 = l1->next;
        else
            l2 = l2->next;
        l3 = l3->next;
    }
    l3 ->next = l1 == NULL?l2:l1;
    return head;
}