/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pHead1 ListNode类 
     * @param pHead2 ListNode类 
     * @return ListNode类
     */
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
        ListNode* temp;ListNode*head;ListNode* p1;ListNode*p2;
        if (pHead1==nullptr||pHead2==nullptr) {
            if (pHead1==nullptr&&pHead2==nullptr) {
                return nullptr;
            }else if (pHead1==nullptr) {
                return pHead2;
            }else if (pHead2==nullptr) {
                return pHead1;
            }else {
                cout<<"error2"<<endl;
            }
        }
        if (pHead1->val<=pHead2->val) {
            head=pHead1;temp=head;p1=pHead1->next;p2=pHead2;
        }else {
            head=pHead2;temp=head;p1=pHead1;p2=pHead2->next;
        }// write code here
        while (p1!=nullptr&&p2!=nullptr) {
            if (p1->val<=p2->val) {
                temp->next=p1;temp=p1;p1=p1->next;
            }else {
                temp->next=p2;temp=p2;p2=p2->next;
            }
        }
        if (p1==nullptr) {
            while (p2!=nullptr) {
                temp->next=p2;temp=p2;p2=p2->next;
            }
        }else if (p2==nullptr) {
            while (p1!=nullptr) {
                temp->next=p1;temp=p1;p1=p1->next;
            }
        }else {
            cout<<"error1"<<endl;
        }
        temp->next=nullptr;
        return head;
    }
};