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;
}
相关推荐
寻寻觅觅☆11 分钟前
东华OJ-基础题-104-A == B ?(C++)
开发语言·c++
lightqjx21 分钟前
【C++】unordered系列的封装
开发语言·c++·stl·unordered系列
天天爱吃肉821835 分钟前
跟着创意天才周杰伦学新能源汽车研发测试!3年从工程师到领域专家的成长秘籍!
数据库·python·算法·分类·汽车
zh_xuan36 分钟前
kotlin lazy委托异常时执行流程
开发语言·kotlin
alphaTao1 小时前
LeetCode 每日一题 2026/2/2-2026/2/8
算法·leetcode
甄心爱学习1 小时前
【leetcode】判断平衡二叉树
python·算法·leetcode
阿猿收手吧!1 小时前
【C++】string_view:高效字符串处理指南
开发语言·c++
颜酱1 小时前
从二叉树到衍生结构:5种高频树结构原理+解析
javascript·后端·算法
不知名XL1 小时前
day50 单调栈
数据结构·算法·leetcode
玄同7651 小时前
我的 Trae Skill 实践|使用 UV 工具一键搭建 Python 项目开发环境
开发语言·人工智能·python·langchain·uv·trae·vibe coding