leetcode 21 Merge Two Sorted Lists 合并两个有序链表

描述:

合并两个有序链表。

解决:

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    if (!l1)
        return l2;
    if (!l2)
        return l1;
    if (!l1 && !l2)
        return NULL;

    ListNode* ret = new ListNode(0);
    ListNode* now = ret;
    while (l1 || l2) {
        if (!l1) {
            now->next = l2;
            break;
        }
        else if (!l2) {
            now->next = l1;
            break;
        }

        ListNode** min = l1->val <= l2->val?&l1:&l2;
        now->next = *min;
        auto save = (*min)->next;
        (*min)->next = NULL;
        *min = save;
        now = now->next;
    }
    return ret->next;
}

 

posted on 2018-01-22 11:02  willaty  阅读(107)  评论(0编辑  收藏  举报

导航