题解 | #合并两个排序的链表#

合并两个排序的链表

http://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337

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

/*
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;
    }
};
全部评论

相关推荐

昨天 18:54
门头沟学院 Java
点赞 评论 收藏
分享
11-04 14:10
东南大学 Java
_可乐多加冰_:去市公司包卖卡的
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务