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;
}
相关推荐
普通攻击往后拉8 小时前
Leetcode 206. 反转链表
算法·leetcode·链表
Nebula嵌入式9 小时前
【C语言】09-深入解析main函数
linux·c语言·开发语言·嵌入式
@syh.9 小时前
【贪心】矩阵消除游戏
算法·游戏·矩阵
可编程芯片开发9 小时前
基于零极点配置的PID控制系统simulink建模与仿真
算法
徐小夕10 小时前
开源!我用SQLite + DuckDB打造了一款可视化AI问数平台
前端·算法·github
Hrain-AI10 小时前
2026 企业 AI 智能体平台横评:8 大主流平台 7 维度实测对比
人工智能·算法·机器学习
天空'之城11 小时前
C 语言工业级通用组件手写 23:卡尔曼滤波(简易版)
c语言·卡尔曼滤波·嵌入式算法·工业级组件
Angel Q.11 小时前
因子分析和生成模型有什么关系?从“幕后因素”到“生成数据”
算法
888CC++11 小时前
C语言与C++的区别:从面向过程到面向对象
java·c语言·c++