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 定义的结构体,如果使用指针了, 如何初始化一个实例?


struct ListNode {
   int val;
   struct ListNode *next;
 };

这个写法就不行!

struct ListNode *head = {NULL, NULL};

正确的写法是:

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

完整代码

/**
 * 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语言 合并2有序

    2024-07-18 22:00:04       24 阅读
  2. C++合并K有序

    2024-07-18 22:00:04       38 阅读
  3. Leetcode:合并有序

    2024-07-18 22:00:04       26 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-18 22:00:04       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-18 22:00:04       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-18 22:00:04       57 阅读
  4. Python语言-面向对象

    2024-07-18 22:00:04       68 阅读

热门阅读

  1. SVN泄露

    2024-07-18 22:00:04       23 阅读
  2. 【ZMH的学习笔记】修饰符类型

    2024-07-18 22:00:04       19 阅读
  3. .Net C# Using 关键字的介绍与使用

    2024-07-18 22:00:04       21 阅读
  4. 前端实现将多个页面导出为pdf(分页)

    2024-07-18 22:00:04       19 阅读
  5. .NET_依赖注入_相关概念及基础使用

    2024-07-18 22:00:04       22 阅读
  6. ES6模块化方案导入导出模块方法

    2024-07-18 22:00:04       21 阅读
  7. 设备树节点和struct device的关系及示例

    2024-07-18 22:00:04       18 阅读
  8. Html_Css问答集(8)

    2024-07-18 22:00:04       18 阅读
  9. APP开发者选择苹果企业签名的理由是什么?

    2024-07-18 22:00:04       21 阅读
  10. 负载均衡轮询逻辑

    2024-07-18 22:00:04       19 阅读
  11. swift小知识点(二)

    2024-07-18 22:00:04       18 阅读