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 小时前
C++ 中的循环语句详解:while、do...while、for、嵌套循环与循环控制
开发语言·c++·算法
不做无法实现的梦~3 小时前
运动控制系统复习一览-----常考题目总结版本
算法
小短腿的代码世界3 小时前
信号路由风暴:Qt算法交易系统的高频信号分发架构
qt·算法·架构
阿文的代码库3 小时前
一文读懂GROUP BY 1,2 VS GROUP BY column_1, column_2 的区别
算法
SuperByteMaster3 小时前
uart中断发送和接收处理
c语言
008爬虫实战录4 小时前
【码上爬】 题十:魔改算法 堆栈分析,找加密值过程详解
前端·python·算法
chao1898444 小时前
基于狮蚁群算法(ALO)的火电机组功能调度实现
人工智能·算法
Deep-w4 小时前
【MATLAB】含光伏 - 储能的家庭/工业微电网能量管理仿真研究
开发语言·算法·matlab
阿文的代码库4 小时前
换根技巧实例分析:最小高度树
算法·动态规划
dyxal4 小时前
Louvain 算法:让网络自己“报团取暖”的发现者
开发语言·算法