剑指offer 合并两个排序的链表

class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        if(pHead1 == nullptr) return pHead2;
        if(pHead2 == nullptr) return pHead1;
        ListNode* res = nullptr;
        if ( pHead1->val <= pHead2->val){
            res = pHead1;
            pHead1 = pHead1->next;
        }
        else {
            res = pHead2;
            pHead2 = pHead2->next;
        }
        ListNode* root = res;
        while ( pHead1 != nullptr && pHead2 != nullptr){
            if(pHead1->val <= pHead2->val){
                root->next = pHead1;
                root = root->next;
                pHead1 = pHead1->next;
            }
            else{
                root->next = pHead2;
                root = root->next;
                pHead2 = pHead2->next;
            }
        }
        if(pHead1 == nullptr){
            root->next = pHead2;
        }
        else{
            root->next = pHead1;
        }
        return res;
    }
};

posted @ 2018-08-25 19:48  一条图图犬  阅读(79)  评论(0编辑  收藏  举报