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;
}
相关推荐
poggioxay1 分钟前
JAVA零基础入门知识3(持续更新中)
java·开发语言·python
鹤归时起雾.5 分钟前
Vue3响应式编程核心指南
开发语言·vue3
im_AMBER7 分钟前
Leetcode 67 长度为 K 子数组中的最大和 | 可获得的最大点数
数据结构·笔记·学习·算法·leetcode
charlie11451419122 分钟前
深入理解CC++的编译与链接技术8:Windows和Linux是如何搜寻动态库的?
c语言·c++·动态库·编译·编译技术
郝学胜-神的一滴24 分钟前
Linux信号四要素详解:从理论到实践
linux·服务器·开发语言·网络·c++·程序人生
yangpipi-24 分钟前
《C++并发编程实战》 第3章 在线程间共享数据
开发语言·c++
fish_xk26 分钟前
c++基础
开发语言·c++
MoonBit月兔26 分钟前
审美积累 | MoonBit LOGO 投稿作品速递
开发语言·编程·moonbit
缘三水1 小时前
【C语言】12.指针(2)
c语言·开发语言·指针
Python学习导航1 小时前
Python开源项目月排行 2025年10月
开发语言·python