合并两个排序的列表

原文地址: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

原文地址:https://www.cnblogs.com/cherrychenlee/p/10780974.html