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;
}
相关推荐
光影少年3 分钟前
AI Agent、自动化与未来工作
人工智能·算法·架构
牧羊人.33314 分钟前
计算机视觉基础 第16章|EigenFace,FisherFace,LBPH传统人脸识别算法
人工智能·算法·计算机视觉
jeo陽18 分钟前
04-循环实战:素数、最大公约数、级数求和与枚举法
c语言·开发语言·数据结构
Nil20826 分钟前
leetcode 72编辑距离
算法·leetcode·职场和发展
神工坊43 分钟前
技术分享︱SIMFORGE HSF® 网格加密与热点加速技术实践
算法·hpc·网格·cae·工程仿真·数值引擎·samr
Nil2081 小时前
leetcode 136只出现一次的数字
leetcode·哈希算法·散列表
CV@CV1 小时前
世界模型与智能体协同推理逻辑
人工智能·算法·边缘计算·量子计算·具身智能
jiayoushijie-泽宣1 小时前
SHIFT-PathFormer:专家轨迹蒸馏、连续安全优化与超大迷宫实验
算法
UIU1142 小时前
P1003 [NOIP 2011 提高组] 铺地毯
数据结构·c++·算法
爱读书的小胖2 小时前
LeetCode 88. 合并两个有序数组 C 解题分析
c语言·数据结构·算法