剑指OFFER之合并两个排序的链表

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

解决办法

1、递归方法:

if(pHead1==NULL)
            return pHead2;
        else if(pHead2==NULL)
            return pHead1;
        ListNode* pMerge=NULL;
        if(pHead1->val<=pHead2->val){
            pMerge=pHead1;
            pMerge->next=Merge(pHead1->next,pHead2);
        }
        else{
            pMerge=pHead2;
            pMerge->next=Merge(pHead1,pHead2->next);
        }
        return pMerge;

2、非递归方法:

if(pHead1==NULL)
           return pHead2;
        if(pHead2==NULL)
            return pHead1;
        ListNode* pRet=NULL;
        ListNode* pMerge=NULL;
        if(pHead1->val<=pHead2->val){
            pMerge=pHead1;
            pHead1=pHead1->next;
        }
        else{
            pMerge=pHead2;
            pHead2=pHead2->next;
        }
        pRet=pMerge;
        while(pHead1&&pHead2){
            if(pHead1->val<=pHead2->val){
                pRet->next=pHead1;
                pHead1=pHead1->next;
                pRet=pRet->next;
            }
            else{
                pRet->next=pHead2;
                pHead2=pHead2->next;
                pRet=pRet->next;
            }
        }
        if(pHead1==NULL)
            pRet->next=pHead2;
        if(pHead2==NULL)
pRet
->next=pHead1; return pMerge;


本解法困扰了我很久,因为开始时我只设置了一个pMerge指针,而没有设置pRet指针,结果运行后发现,如果是两个等长的序列,那么函数返回的结果只有两个序列的最后一个元素,我折腾了好久才明白,pRet是合并链表的工作指针,函数运行完成后它保存的就是链表的尾元素,而合并链表的真正的头指针是pMerge指针,它才是函数真正的返回结果。

 

posted @ 2016-08-27 21:12  justDoIT&  阅读(196)  评论(0编辑  收藏  举报