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

    原文地址:https://www.jianshu.com/p/58e525cefbab

    时间限制:1秒 空间限制:32768K

    题目描述

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

    我的代码

    /*
    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)
                return pHead2;
            if(pHead2==nullptr)
                return pHead1;
            if(pHead1->val<pHead2->val){
                pHead1->next=Merge(pHead1->next,pHead2);
                return pHead1;
            }
            else{
                pHead2->next=Merge(pHead1,pHead2->next);
                return pHead2;
            }
        }
    };
    

    运行时间:3ms
    占用内存:460k

    /*
    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)
                return pHead2;
            if(pHead2==nullptr)
                return pHead1;
            ListNode* mergeHead=nullptr;
            ListNode* cur=nullptr;
            while((pHead1!=nullptr)&&(pHead2!=nullptr)){
                if(pHead1->val<pHead2->val){
                    if(mergeHead==nullptr)
                        mergeHead=cur=pHead1;
                    else{
                        cur->next=pHead1;
                        cur=cur->next;
                    }
                    pHead1=pHead1->next;
                }
                else{
                    if(mergeHead==nullptr)
                        mergeHead=cur=pHead2;
                    else{
                        cur->next=pHead2;
                        cur=cur->next;
                    }
                    pHead2=pHead2->next;
                }
            }
            if(pHead1!=nullptr){
                cur->next=pHead1;
            }
            if(pHead2!=nullptr){
                cur->next=pHead2;
            }
         return mergeHead;        
        }
    };
    

    运行时间:3ms
    占用内存:476k

  • 相关阅读:
    杀死初创科技公司的四大工程陷阱
    杀死初创科技公司的四大工程陷阱
    Linux中su和sudo的用法整理
    Linux中su和sudo的用法整理
    Docket 使用命令
    Docker 部署 portainer
    Linux 双网卡绑定
    docker安装部署,阿里源加速
    nmcli详解
    搭建LAMP环境示例
  • 原文地址:https://www.cnblogs.com/cherrychenlee/p/10780974.html
Copyright © 2011-2022 走看看