【算法】剑指offer- JZ25 合并两个排序的链表

题目链接

输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。

在这里插入图片描述

法一:迭代

每一次循环中,取较小数值的结点,尾插到新链表后。

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
        if(nullptr == pHead1)
            return pHead2;
        if(nullptr == pHead2)
            return pHead1;
        
        ListNode* newtail = nullptr;
        ListNode* newhead = nullptr;
        
        while(pHead1 && pHead2)
        {
            ListNode* cur = nullptr;
            
            if(pHead1->val < pHead2->val)
            {
                cur = pHead1;
                pHead1 = pHead1->next;
            }
            else
            {
                cur = pHead2;
                pHead2 = pHead2->next;              
            }

            // 插入结点
            if(newhead == nullptr)
            {
                newhead = cur;
                newtail = cur;
                cur->next = nullptr;
            }
            else
            {
                // 不是空链表
                newtail->next = cur;
                cur->next = nullptr;
                newtail = cur;
            }
        }
        
        if(pHead1)
        {
            // 1链表还存在
            newtail->next = pHead1;
        }
        
        if(pHead2)
        {
            newtail->next = pHead2;
        }
        
        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 == nullptr)
            return pHead2;
        
        if(pHead2 == nullptr)
            return pHead1;
        
        ListNode* newhead = nullptr, *newtail = nullptr;
        ListNode* cur = pHead1->val < pHead2->val ? pHead1 : pHead2;
        
        if(cur == pHead1)
        {
            pHead1 = pHead1->next;
        }
        else if(cur == pHead2)
        {
            pHead2 = pHead2->next;
        }
        
        if(newhead == nullptr)
        {
            newhead = cur;
            newtail = cur;
            newtail->next = nullptr;
        }
        else
        {
            newtail->next = cur;
            newtail = cur;
            cur->next = nullptr;
        }
        
        newtail->next = Merge(pHead1, pHead2);
        
        return newhead;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JoyCheung-

赏颗糖吃吧~~~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值