zoukankan      html  css  js  c++  java
  • 排序两个排序的链表----递归非递归实现

     ListNode* Merge1(ListNode* pHead1, ListNode* pHead2)
     {
         if(pHead1 == NULL)
             return pHead2;
         else if(pHead2 == NULL)
             return pHead1;
         
         ListNode* pMergedHead = NULL;
         
         if(pHead1->m_nValue < pHead2->m_nValue)
         {
             pMergedHead = pHead1;
             pMergedHead->m_pNext = Merge1(pHead1->m_pNext, pHead2);
         }
         else
          {
             pMergedHead = pHead2;
             pMergedHead->m_pNext = Merge1(pHead1, pHead2->m_pNext);
          }
         
         return pMergedHead;
     }
       ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
        {
          if(pHead1 == NULL)
             return pHead2;
          if(pHead2 == NULL)
              return pHead1;
     
          ListNode* NewHead=NULL;
            ListNode* temp=NULL;
            ListNode* pNode1 = pHead1;
            ListNode* pNode2 = pHead2;
            while(pNode1!=NULL && pNode2!=NULL)
            {
                if(NewHead==NULL)
                {
                    if(pNode1->val <= pNode2->val)
                    {
                        NewHead =pNode1;
                        pNode1 = pNode1->next;
                    }
                    else
                    {
                        NewHead =pNode2;
                        pNode2 = pNode2->next;
                    }
                    temp=NewHead;
                }
                else
                {
                    if(pNode1->val <= pNode2->val)
                    {
                        temp->next=pNode1;
                        pNode1=pNode1->next;
                        //temp->next=NULL;
                        temp=temp->next;
                    }
                    else 
                    {
                        temp->next=pNode2;
                        pNode2=pNode2->next;
                        //temp->next=NULL;
                        temp=temp->next;
                    }
                }
     
            }
            if(pNode1==NULL && pNode2!=NULL)
                temp->next=pNode2;
            else if(pNode2==NULL && pNode1!=NULL)
                temp->next=pNode1; 
                
            return NewHead;
        }
  • 相关阅读:
    ESP32学习目录
    python中mysql管理模块mysql-connector使用
    MYSQL基础知识和操作
    urlib补充
    Python3中Urllib库是什么?urllib模块基本使用
    递归:斐波契那数列
    python正则模块一
    模块&包
    XML模块示例代码
    使用python操作XML增删改查
  • 原文地址:https://www.cnblogs.com/xiaodi914/p/5797200.html
Copyright © 2011-2022 走看看