C语言 | Leetcode C语言题解之第2题两数相加

题目:

题解:

cpp 复制代码
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode *head = NULL, *tail = NULL;
    int carry = 0;
    while (l1 || l2) {
        int n1 = l1 ? l1->val : 0;
        int n2 = l2 ? l2->val : 0;
        int sum = n1 + n2 + carry;
        if (!head) {
            head = tail = malloc(sizeof(struct ListNode));
            tail->val = sum % 10;
            tail->next = NULL;
        } else {
            tail->next = malloc(sizeof(struct ListNode));
            tail->next->val = sum % 10;
            tail = tail->next;
            tail->next = NULL;
        }
        carry = sum / 10;
        if (l1) {
            l1 = l1->next;
        }
        if (l2) {
            l2 = l2->next;
        }
    }
    if (carry > 0) {
        tail->next = malloc(sizeof(struct ListNode));
        tail->next->val = carry;
        tail->next->next = NULL;
    }
    return head;
}
相关推荐
星轨初途6 小时前
数据结构排序算法详解(5)——非比较函数:计数排序(鸽巢原理)及排序算法复杂度和稳定性分析
c语言·开发语言·数据结构·经验分享·笔记·算法·排序算法
人类发明了工具7 小时前
【机器人-激光雷达】点云时间运动补偿
算法·机器人
f***01937 小时前
CC++链接数据库(MySQL)超级详细指南
c语言·数据库·c++
north_eagle8 小时前
向量搜索技术深度研究报告:架构原理、核心算法与企业级应用范式
算法·架构
椰萝Yerosius8 小时前
[题解]2024CCPC郑州站——Z-order Curve
c++·算法
小曹要微笑8 小时前
STM32F7 时钟树简讲(快速入门)
c语言·stm32·单片机·嵌入式硬件·算法
南山安8 小时前
栈(Stack):从“弹夹”到算法面试题的进阶之路
javascript·算法·面试
2301_764441339 小时前
Python构建输入法应用
开发语言·python·算法
AI科技星9 小时前
为什么变化的电磁场才产生引力场?—— 统一场论揭示的时空动力学本质
数据结构·人工智能·经验分享·算法·计算机视觉
TheLegendMe10 小时前
贪心+线程安全单例
算法·哈希算法