合并有序链表

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        if(pHead1 == nullptr) return pHead2;
        if(pHead2 == nullptr) return pHead1;
        ListNode *res = new ListNode(-1);
        ListNode *p = res;
        ListNode *temp;
        while(pHead1 != nullptr && pHead2 != nullptr) {
            if(pHead1->val <= pHead2->val) {
                temp = pHead1;
                pHead1 = pHead1->next;
                p->next = temp;
            } else{
                temp = pHead2;
                pHead2 = pHead2->next;
                p->next = temp;
            }
            p = p->next;
        }

        if(pHead1 != nullptr && pHead2 == nullptr){
            p->next = pHead1;
        }
        if(pHead1 == nullptr && pHead2 != nullptr){
            p->next = pHead2;
        }
        return res->next;
    }
};

你可能感兴趣的:(合并有序链表)