首页 > 编程语言 > 详细

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

时间:2016-08-27 22:07:56      阅读:231      评论:0      收藏:0      [点我收藏+]

题目描述

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

解决办法

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指针,它才是函数真正的返回结果。

 

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

原文:http://www.cnblogs.com/mj-selina/p/5813818.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!