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;
}
相关推荐
先知后行。8 小时前
C/C++八股文
java·开发语言
程序员buddha8 小时前
C语言数组详解
c语言·开发语言·算法
寻找华年的锦瑟8 小时前
Qt-视频播放器
开发语言·qt
又是忙碌的一天9 小时前
Java IO流
java·开发语言
fish_study_csdn9 小时前
Python内存管理机制
开发语言·python·c python
蒙奇D索大10 小时前
【算法】递归算法的深度实践:从布尔运算到二叉树剪枝的DFS之旅
笔记·学习·算法·leetcode·深度优先·剪枝
卡提西亚10 小时前
C++笔记-25-函数模板
c++·笔记·算法
ghie909010 小时前
MATLAB/Simulink水箱水位控制系统实现
开发语言·算法·matlab
cs麦子11 小时前
C语言--详解--指针--上
c语言·开发语言
像风一样自由202011 小时前
Go语言入门指南-从零开始的奇妙之旅
开发语言·后端·golang