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

  • 相关阅读:
    HDU-1115计算几何
    树形DP入门之HDU 1296
    拓扑排序-POJ1964
    其他一些数状数组的题
    HDU 2852(树状数组plus二分)
    POJ-2155二维树状数组
    HDOJ 1166 敌兵布阵 (线段树)
    codevs 1082 线段树练习3 (线段树)
    codevs 1081 线段树练习2 (线段树)
    codevs 1080 线段树练习(线段树)
  • 原文地址:https://www.cnblogs.com/cherrychenlee/p/10780974.html
Copyright © 2011-2022 走看看