LeetCodehot100-21 合并两个有序链表

复制代码
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        if(list1==nullptr||list2==nullptr){
            return list1==nullptr?list2:list1;
        }
        ListNode* head=list1->val<=list2->val?list1:list2;
        ListNode* cur1=head->next;
        ListNode* cur2=head==list1?list2:list1;
        ListNode* tmp=head;
        while(cur1!=nullptr&&cur2!=nullptr){
            if(cur1->val<=cur2->val){
                tmp->next=cur1;
                cur1=cur1->next;
            }
            else{
                tmp->next=cur2;
                cur2=cur2->next;
            }
            tmp=tmp->next;
        }
        tmp->next=cur1==nullptr?cur2:cur1;
        return head;
    }
};

递归:

复制代码
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        if(list1==nullptr) return list2;
        if(list2==nullptr) return list1;
        if(list1->val<=list2->val){
            list1->next=mergeTwoLists(list1->next,list2);//返回的后面的有序链表中的第一个点
            return list1;
        }
        else{
            list2->next=mergeTwoLists(list1,list2->next);
            return list2;
        }
    }
};
相关推荐
Dillon Dong1 小时前
【风电控制】TI TMS320F28379D 双CPU架构解析与任务分布设计
嵌入式硬件·算法·变流器·风电控制
小羊在睡觉7 小时前
力扣84. 柱状图中最大的矩形
后端·算法·leetcode·golang·go
3DVisionary7 小时前
蓝光三维扫描:医疗制造的精度焦虑怎么解
人工智能·算法·制造·蓝光三维扫描·医疗制造·三维检测·义齿检测
好评笔记7 小时前
机器学习面试八股——常用损失函数
人工智能·深度学习·算法·机器学习·校招
weixin_468466857 小时前
全局与局部注意力机制新手实战指南
人工智能·python·深度学习·算法·自然语言处理·transformer·注意力机制
_日拱一卒7 小时前
LeetCode:994腐烂的橘子
java·数据结构·算法·leetcode·深度优先
珂朵莉MM8 小时前
第七届全球校园人工智能算法精英大赛-算法巅峰赛产业命题赛第3赛季优化题--束搜索
人工智能·算法
Omics Pro9 小时前
首个!外源天然产物综合性代谢图谱
数据库·人工智能·算法·机器学习·r语言
voidmort9 小时前
3. 微调(Fine-tuning)与强化学习(RL)的核心思想
python·深度学习·算法
人道领域9 小时前
【LeetCode刷题日记】669.修剪二叉搜索树
开发语言·python·算法