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;
}
相关推荐
专注仿真2 小时前
引擎扩展性与集成设计深度剖析:从 14 个扩展点到 DIS→HLA 演进之路
开发语言·算法·仿真引擎·推演引擎
码爸3 小时前
支持向量机介绍与示例
算法·机器学习·支持向量机
怕浪猫3 小时前
2028编程圈很火的10个Skills
算法·面试·github
Best-Wishes3 小时前
科来网络分析系统(技术交流版)使用说明书
开发语言·junit·php
代码不停3 小时前
自动化测试(java)
java·开发语言·selenium·自动化
鬼手点金5 小时前
opencode-rules 插件
java·开发语言·前端·人工智能·chrome·git·github
爱上网的小舟5 小时前
星际战士2启动错误怎么办?5种游戏报错解决方法
开发语言·php
阿里嘎多学长6 小时前
2026-10-12 GitHub 热点项目精选
开发语言·程序员·github·代码托管
wangchunyu1147 小时前
Python 数据可视化实战入门教程
开发语言·python·信息可视化
Nil2087 小时前
leetcode 198打家劫舍
算法·leetcode·职场和发展