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

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

题目描述

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

示例 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;
}
相关推荐
晴天的雨.99220 分钟前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
aramae7 小时前
MySQL复合查询(8)
java·c语言·开发语言·后端·算法
荆棘鸟智能8 小时前
城市感知设备怎么统一接入?从多协议网关到设备模型的中间件架构设计
人工智能·算法·边缘计算
无敌贵点大王8 小时前
RTThread学习记录11——RT-Thread 设备模型吃透:UART/ADC/PWM/PIN 到底有什么区别?
c语言·stm32·学习·链表
淡海水8 小时前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1018 小时前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
INGNIGHT12 小时前
270 · 电话号码的字母组合II(Trie)
linux·算法
2401_8390805412 小时前
C++常见八股
数据结构·c++·算法
青山是哪个青山12 小时前
LeetCode 188:买卖股票的最佳时机 IV
算法
暮雨封夕12 小时前
跳表(Skip List)详解:原理、实现、使用场景与实际应用
数据结构