zoukankan      html  css  js  c++  java
  • 合并两个排序的链表

    1.递归求解

    /*
    struct ListNode {
        int val;
        struct ListNode *next;
        ListNode(int x) :
                val(x), next(NULL) {
        }
    };*/
    class Solution {
    public:
        ListNode* Merge(ListNode* pHead1, ListNode* pHead2)//两个链表长度不一样
        {
           if(pHead1==nullptr &&pHead2==nullptr)
            return  nullptr;  
            if(pHead1==nullptr)
            return pHead2;
            if(pHead2==nullptr)
            return pHead1;
            
            //开始递归求   //要定义一个辅助的量  将排好序的放在里面
            ListNode* pMergehead=nullptr;//归并后的
           if(pHead1->val<=pHead2->val) 
            {
               pMergehead=pHead1; 
               pMergehead->next= Merge(pHead1->next,pHead2);//递归一般都于高向低 内部
            }
            else {
                pMergehead=pHead2;
                pMergehead->next= Merge(pHead1,pHead2->next);
            }
       
        return  pMergehead;
        }
    };

    2. 非递归    注意顺序 将==NULL放在最后,  满足的也是一开始就进去了!!!

    /*
    struct ListNode {
        int val;
        struct ListNode *next;
        ListNode(int x) :
                val(x), next(NULL) {
        }
    };*/
    class Solution {
    public:
        ListNode* Merge(ListNode* pHead1, ListNode* pHead2)//两个链表长度不一样
        {
    
      //新建一个头节点,用来存合并的链表。
            ListNode * head=new ListNode(-1);
            head->next=NULL;
            ListNode * root=head;
            while(pHead1!=NULL&&pHead2!=NULL){//都不为null
                if(pHead1->val<pHead2->val){
                    head->next=pHead1;
                    head=head->next;
                    pHead1=pHead1->next;
                }else{
                    head->next=pHead2;
                    head=head->next;
                    pHead2=pHead2->next;
                }
            }
            //把未结束的链表连接到合并后的链表尾部
            if(pHead1!=NULL){
                head->next=pHead1;
            }
            if(pHead2!=NULL){
                head->next=pHead2;
            }
            return root->next;
        }
    };
  • 相关阅读:
    MS SQL Server2012中的TRY_CONVERT函数
    MS SQL Server2012中的CONCAT函数
    查询数据库大小
    显示数据与存储方式
    Windows 8 安装之后怎样更改产品码
    IIS SubStatus Codes
    MS SQL Server Quarter Function
    程序中处理一对多的数据
    找出字符串中所有数字
    BOOTMGR is missing
  • 原文地址:https://www.cnblogs.com/cgy1012/p/11385622.html
Copyright © 2011-2022 走看看