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;
}
相关推荐
想做小南娘,发现自己是女生喵1 小时前
第 2 章 顺序表和 vector
java·数据结构·算法
ComputerInBook1 小时前
c 和 c++ 中的宏块(macro)
c语言·c++··宏块·宏指令
艾醒2 小时前
2026年第29周(7.13-7.19)AI全复盘:技术突破、行业趣闻翻车、算力服务器商业动态
人工智能·算法
雪碧聊技术2 小时前
动态规划算法—01背包问题
算法·动态规划
bu_shuo2 小时前
c与cpp中的argc和argv
c语言·c++·算法
普贤莲花2 小时前
【2026年第29周---写于20260718】---整理,断舍离
程序人生·算法·生活
Reart2 小时前
Leetcode 674.最长连续递增序列 (719)
后端·算法
Aurorar0rua2 小时前
CS50 x 2024 Notes Algorithms - 02
c语言·开发语言·学习方法
Reart3 小时前
Leetcode 300.最长递增子序列(719)
算法
可编程芯片开发3 小时前
VSG虚拟同步发电机simulink建模与仿真
算法