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;
}
相关推荐
SilentSamsara4 分钟前
自定义上下文管理器实战:数据库连接池、文件锁与超时控制
开发语言·python·算法·青少年编程
吃着火锅x唱着歌12 分钟前
LeetCode 503.下一个更大元素II
算法·leetcode·职场和发展
我还记得那天13 分钟前
1 初识C语言
c语言
_深海凉_16 分钟前
LeetCode热题100-将有序数组转换为二叉搜索树
数据结构·算法·leetcode
KaMeidebaby25 分钟前
卡梅德生物技术快报|单克隆抗体人源化 PEG 修饰质控方法体系构建与验证
服务器·前端·数据库·人工智能·算法·百度·新浪微博
不知名的老吴40 分钟前
二叉树的遍历算法之先序遍历
算法
liu****42 分钟前
第16届国赛蓝桥杯大赛C/C++大学B组
c语言·数据结构·c++·算法·蓝桥杯
SimpleLearingAI1 小时前
大模型推理框架总结解析
算法
Σίσυφος19001 小时前
正则化数据并校准数据
人工智能·算法·机器学习
HZ·湘怡1 小时前
基于动态数组的栈(顺序栈)01
数据结构·算法