牛客网《剑指Offer》编程 16. 合并两个有序链表

 

题目描述

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

基本思路

设置一个头结点newHead,newHead初始化乘两个链表中头结点较小的节点。

当第一个链表中的节点值小于等于第二个时,

                      将newHead指向第一个链表节点;

                      调整正newHead指针和第一个链表的节点指针。

当第二个链表中节点值小于第一个时,

                      将newHead指向第二个链表节点;

                      调整newHead指针和第二个链表节点指针。

如果第一个或者第二个链表最后剩下残余的链表,将它连接到新链表后面。

 备注:本算法有递归和非递归两种实现方式。时间复杂度为O(n),由于只生成了头结点,没有生成其他新的节点,因此空间复杂度为O(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){
            return pHead2;
        }else if(!pHead2){
            return pHead1;
        }else{
            ListNode* newHead,*p;
            if(pHead1->val<=pHead2->val){
                newHead=pHead1;
                pHead1=pHead1->next;
            }else{
                newHead=pHead2;
                pHead2-pHead2->next;
            }
            p=newHead;
            while(pHead1&&pHead2){
                if(pHead1->val<=pHead2->val){
                    p->next=pHead1;
                    pHead1=pHead1->next;
                    
                }else{
                    p->next=pHead2;
                    pHead2=pHead2->next;
                    
                }
                p=p->next;
            }
            if(!pHead1){
                p->next=pHead2;
            }
            if(!pHead2){
                p->next=pHead1;
            }
            return newHead;
        }
    }
};
/*
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){return pHead2;}
        if(!pHead2){return pHead1;}
        ListNode* newHead;
        if(pHead1->val<=pHead2->val){
            newHead=pHead1;
            newHead->next=Merge(pHead1->next,pHead2);
        }else{
            newHead=pHead2;
            newHead->next=Merge(pHead1,pHead2->next);
        }
        return newHead;
    }
};

猜你喜欢

转载自blog.csdn.net/eriHanami/article/details/82669632