zoukankan      html  css  js  c++  java
  • 剑指offer16-合并两个排序链表

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

    思路:递归和非递归方式

        ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
        {
              if(pHead1==NULL) return pHead2;
            if(pHead2==NULL) return pHead1;
            ListNode *pHead3=NULL,*p3=NULL;//这里牛客网测试时,不初始化为null,将无法通过测试
            while(pHead1!=NULL&&pHead2!=NULL)
            {
                if(pHead1->val<=pHead2->val)
                {
                    if(pHead3==NULL)
                    {
                        p3=pHead1;
                        pHead3=p3;//=pHead1;
                    }
                    else {
                        p3->next=pHead1;
                        p3=p3->next;
                    }
                    pHead1=pHead1->next;
                 }
                 else
                 {
                     if(!pHead3)
                     {
                       p3=pHead2;
                       pHead3=p3;
                         
                     }else {
                        p3->next=pHead2;
                        p3=p3->next;
                    }
                    pHead2=pHead2->next;
                 }
            }
            if(pHead1==NULL)
            {
                p3->next=pHead2;
            }
            if(pHead2==NULL){
                p3->next=pHead1;
            }
            return pHead3;
        }

            //递归

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

  • 相关阅读:
    设计模式(Design Pattern)扫盲
    SharePoint 2007 采用表单验证 (1) 失败:(
    发布一款给图片批量加水印的程序PicNet V1.0
    转篇文章,VS2005开发的dll如何安装进GAC
    cnblogs排名进入1500,纪念一下
    转载一篇提高baidu/google收录的文章
    关于.NET(C#)中字符型(Char)与数字类型的转换, CLR via c# 读书笔记
    《天风文章》V1.2.0 新闻/文章类asp.net2.0站点系统源码 (100%开源)
    推荐个.Net的论坛系统 Discuz!NT
    C#实现对图片加水印的一段代码.
  • 原文地址:https://www.cnblogs.com/trouble-easy/p/12965562.html
Copyright © 2011-2022 走看看