链表的归并排序。对第一个结点需要特殊处理。每次比较链表两个指针的值,将值小的放入结果链表,并将其指针后移。这样做是直接照搬数组的归并排序。

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