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;
}
相关推荐
aaaameliaaa7 小时前
字符函数和字符串函数
c语言·笔记·算法
夜月yeyue7 小时前
AUTOSAR CP 从上电到 Runnable
c语言·网络·tcp/ip·车载系统
城管不管8 小时前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划
月疯9 小时前
二分法算法(水平等分图形面积)
算法
豆瓣鸡9 小时前
算法日记 - Day3
java·开发语言·算法
白白白小纯9 小时前
算法篇—反转链表
c语言·数据结构·算法·leetcode
Achou.Wang9 小时前
深入理解go语言-第5章 并发编程——Go的灵魂
大数据·算法·golang
The Chosen One98510 小时前
高进度算法模板速记(待完善)
java·前端·算法
小羊先生car10 小时前
RTOS-F429-HAL-绝对延时和相对延时(2026/7/31)
c语言·rtos
圣保罗的大教堂12 小时前
leetcode 3517. 最小回文排列 I 中等
leetcode