/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
        if(pHead1==nullptr) return pHead2;
        if(pHead2==nullptr) return pHead1;
        ListNode* head = (pHead1->val <= pHead2->val) 
                         ? pHead1 :pHead2 ;
        ListNode* i = head;
        ListNode* j = (pHead1 == i) ? pHead2 : pHead1;                
        while(i->next && j)
        {
            if(i->next->val >= j->val)
            {
                ListNode* j_next = j->next;
                j->next = i->next;
                i->next = j;
                j = j_next;
            }
            else
            {
                i = i->next;
            }
        }
        if(i->next == nullptr) 
            i->next = j;
        return head;
    }
};