【算法】合并两个有序链表

本题来源---《合并两个有序链表

题目描述

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

示例 1:

复制代码
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{

}

解题思路:

我做这道题的核心思路就是,创建一个新链表,然后依次往里放。

代码如下:

(大家对着图进行分析,效果应该会更好)

复制代码
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
    struct ListNode      *head ,*tail;
    struct ListNode      *l1 = list1;
    struct ListNode      *l2 = list2;

    head = tail = (struct ListNode *)malloc(sizeof(struct ListNode));

    if( !list1 )
    {
        return list2;
    }

    if( !list2 )
    {
        return list1;
    }

    while( l1 && l2 )
    {
        if( l1->val <= l2->val )
        {
            tail->next = l1;
            tail = tail->next;
            l1 = l1->next;
            tail->next = NULL;
        }
        else
        {
            tail->next = l2;
            tail = tail->next;
            l2 = l2->next;
            tail->next = NULL;
        }
    }

    if( l1 )
    {
        tail->next = l1;
    }

    if( l2 )
    {
        tail->next = l2;
    }

    return head->next;
}
相关推荐
格林威18 分钟前
C++ 工业视觉实战:Bayer 图转 RGB 的 3 种核心算法(邻域平均、双线性、OpenCV 源码级优化)
开发语言·c++·人工智能·opencv·算法·计算机视觉·工业相机
Frostnova丶19 分钟前
LeetCode 3643.子矩阵垂直翻转算法解析
算法·leetcode·矩阵
2401_8512729921 分钟前
C++中的模板方法模式
开发语言·c++·算法
2401_8942419221 分钟前
C++中的策略模式进阶
开发语言·c++·算法
爱丽_27 分钟前
G1 深入:Region、Remembered Set、三色标记与“可预测停顿”
java·数据库·算法
sprite_雪碧27 分钟前
简单模拟问题
算法
2401_8747325328 分钟前
C++中的装饰器模式
开发语言·c++·算法
j_xxx404_32 分钟前
力扣--分治(快速排序)算法题II:数组中的第K个最大元素(Top K问题),LCR159.库存管理III
数据结构·c++·算法·leetcode
ysa05103032 分钟前
运用map优化多次查询【Kadomatsu 子序列】
数据结构·c++·笔记·算法
_饭团38 分钟前
C 语言内存函数全解析:从 memcpy 到 memcmp 的使用与模拟实现
c语言·开发语言·c++·学习·算法·面试·改行学it