和归并排序有相似之处

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
        ListNode* pHead = new ListNode(0);// 因为ListNode没有不带值的初始化,所以要new一个头结点值为0的链表
        auto p = pHead;
        while(pHead1 && pHead2) {
            if(pHead1->val < pHead2->val) {
                auto pre = pHead1->next;
                pHead1->next = p->next;
                p->next = pHead1;
                pHead1 = pre;
                p = p->next;
            }
            else {
                auto pre = pHead2->next;
                pHead2->next = p->next;
                p->next = pHead2;
                pHead2 = pre;
                p = p->next;
            }
        }
        while(pHead1){
            auto pre = pHead1->next;
            pHead1->next = p->next;
            p->next = pHead1;
            pHead1 = pre;
            p = p->next;
        }
        while(pHead2){
            auto pre = pHead2->next;
            pHead2->next = p->next;
            p->next = pHead2;
            pHead2 = pre;
            p = p->next;
        }
        return pHead->next; // 返回头结点的下一个节点
    }
};