C语言 合并2个有序链表

题目链接:

https://leetcode.cn/problems/merge-two-sorted-lists/description/?envType=study-plan-v2&envId=selected-coding-interview

参考题解。

https://leetcode.cn/problems/merge-two-sorted-lists/solutions/1734801/by-elegant-franklin6qn-mo0y/?envType=study-plan-v2\&envId=selected-coding-interview

问题记录:

对于一个 struct 定义的结构体,如果使用指针了, 如何初始化一个实例?

cpp 复制代码
struct ListNode {
   int val;
   struct ListNode *next;
 };

这个写法就不行!

struct ListNode *head = {NULL, NULL};

正确的写法是:

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

完整代码

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


// 参考题解。
// https://leetcode.cn/problems/merge-two-sorted-lists/solutions/1734801/by-elegant-franklin6qn-mo0y/?envType=study-plan-v2&envId=selected-coding-interview

 
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
    // struct ListNode *head = {NULL, NULL};

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

    while (true) {
        if (!list1) {
            dummy->next = list2;
            break;
        }
        
        if (!list2) {
            dummy->next = list1;
            break;
        }

        if (list1->val < list2->val) {
            dummy->next = list1;
            list1 = list1->next;
        } else {
             dummy->next = list2;
            list2 = list2->next;
        }

        dummy = dummy->next;

    }
    return head->next;
}
相关推荐
小六子成长记1 分钟前
【C++】:多态的实现
开发语言·c++
flysh051 分钟前
关于C#编程中的async / await关键字
开发语言·c#
好好学操作系统2 分钟前
flash_attn ImportError undefined symbol:
开发语言·python
CCPC不拿奖不改名2 分钟前
面向对象编程:继承与多态+面试习题
开发语言·数据结构·python·学习·面试·职场和发展
꧁Q༒ོγ꧂4 分钟前
算法详解(二)--算法思想基础
java·数据结构·算法
꧁Q༒ོγ꧂5 分钟前
算法详解(一)--算法系列开篇:什么是算法?
开发语言·c++·算法
橘颂TA5 分钟前
【剑斩OFFER】算法的暴力美学——力扣:1047 题:删除字符串中的所有相邻重复项
c++·算法·leetcode·职场和发展·结构于算法
2301_800256115 分钟前
R-Tree创建与遍历,R-Tree在4类空间查询中的应用,实现4类空间查询的各类算法[第8章]
数据库·算法·机器学习·postgresql·r-tree
BFT白芙堂12 分钟前
基于 GPU 并行加速的 pRRTC 算法:赋能 Franka 机械臂的高效、稳定运动规划
人工智能·深度学习·算法·机器学习·gpu·具身智能·frankaresearch3
牛老师讲GIS12 分钟前
多边形简化讲解:从四大核心算法到 Mapshaper 自动化实战
网络·算法·自动化