合并有序链表

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    if (l1 == nullptr){
        return l2;
    }
    
    if (l2 == nullptr){
        return l1;
    }
    
    auto head = l1;
    auto otherHead = l2;
    if (l2->val < l1->val){
        head = l2;
        otherHead = l1;
    }
    
    auto it1 = head;
    auto it2 = otherHead;
    while (it2 != nullptr){
        if (it1->next == nullptr){
            it1->next = it2;
            it2 = it2->next;
            break;
        }
        else if (it2->val > it1->next->val){
            it1 = it1->next;
        }
        else{
            auto tmp = it2;
            it2 = it2->next;
            tmp->next = it1->next;
            it1->next = tmp;
            it1 = it1->next;
        }
    }
    return head;
}

 

posted @ 2015-08-24 16:58  wu_overflow  阅读(113)  评论(0编辑  收藏  举报