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

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

题目描述

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

示例 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;
}

相关推荐

  1. Leetcode:合并有序

    2024-04-23 04:34:01       6 阅读
  2. 数据结构—有序合并排序算法

    2024-04-23 04:34:01       32 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-23 04:34:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-23 04:34:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-23 04:34:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-23 04:34:01       18 阅读

热门阅读

  1. MySQL面试题

    2024-04-23 04:34:01       14 阅读
  2. URL解析

    URL解析

    2024-04-23 04:34:01      16 阅读
  3. MATLAB初学者入门(11)—— 贪心算法

    2024-04-23 04:34:01       18 阅读
  4. Spring Boot 加载本地 JAR 包的技术实践

    2024-04-23 04:34:01       17 阅读
  5. 2024年4月,docker启动新版minio

    2024-04-23 04:34:01       12 阅读