合并两个有序链表(每日一题)

"路虽远,行则将至"

❤️主页:************小赛毛****************

☕今日份刷题:合并两个有序链表

题目描述:

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例1:

cpp 复制代码
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

示例2:

cpp 复制代码
输入:l1 = [], l2 = []
输出:[]

示例3:

cpp 复制代码
输入:l1 = [], l2 = [0]
输出:[0]

题目分析:

这题可太经典了,直接取小的尾插

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
    if(list1 == NULL)
    {
        return list2;
    }
    if(list2 == NULL)
    {
        return list1;
    }
    struct ListNode* head = NULL,*tail = NULL;
    while(list1 && list2)
    {
        //取小的尾插
        if(list1->val < list2->val)
        {
            if(tail == NULL)
            {
                head = tail = list1;
            }
            else
            {
                tail->next = list1;
                tail = tail->next;
            }
            list1 = list1->next;
        }
        else
        {
           
            if(tail == NULL)
            {
                head = tail = list2;
            }
            else
            {
                tail->next = list2;
                tail = tail->next;
            }
            list2 = list2->next;
        }
    }
    if(list1)
    {
        tail->next = list1;
    }
    if(list2)
    {
        tail->next = list2;
    }
    return head;
}
相关推荐
楠秋92021 分钟前
代码随想录算法训练营第三十二天| 509. 斐波那契数 、 70. 爬楼梯 、746. 使用最小花费爬楼梯
数据结构·算法·leetcode·动态规划
㓗冽22 分钟前
最大效益(二维数组)-基础题76th + 螺旋方阵(二维数组)-基础题77th + 方块转换(二维数组)-基础题78th
数据结构·算法
We་ct31 分钟前
LeetCode 25. K个一组翻转链表:两种解法详解+避坑指南
前端·算法·leetcode·链表·typescript
元亓亓亓35 分钟前
LeetCode热题100--239. 滑动窗口最大值--困难
数据结构·算法·leetcode
Renhao-Wan1 小时前
Java 算法实践(三):双指针与滑动窗口
java·数据结构·算法
好学且牛逼的马1 小时前
【Hot100|23-LeetCode 234. 回文链表 - 完整解法详解】
算法·leetcode·链表
fu的博客1 小时前
【数据结构1】实现线性表
数据结构
不想看见4041 小时前
Combinations -- 回溯法--力扣101算法题解笔记
数据结构·算法
凤年徐1 小时前
优选算法——双指针专题 3.快乐数 4.盛水最多的容器
开发语言·数据结构·c++·算法
小亮✿2 小时前
算法—并查集
数据结构·c++·算法