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 小时前
【强化学习实战】第十一章:Gymnasium库的介绍和使用(1)、出租车游戏代码详解(Sarsa & Q learning)
人工智能·python·深度学习·算法·游戏·机器学习
炒鸡菜6666 小时前
程序人生-Hello’s P2P
c语言·程序人生·职场和发展
2401_884602276 小时前
程序人生-Hello’s P2P
c语言·c++
weixin_458872616 小时前
东华复试OJ二刷复盘2
算法
Charlie_lll6 小时前
力扣解题-637. 二叉树的层平均值
算法·leetcode
爱淋雨的男人6 小时前
自动驾驶感知相关算法
人工智能·算法·自动驾驶
wen__xvn7 小时前
模拟题刷题3
java·数据结构·算法
滴滴答滴答答7 小时前
机考刷题之 6 LeetCode 169 多数元素
算法·leetcode·职场和发展
圣保罗的大教堂7 小时前
leetcode 1980. 找出不同的二进制字符串 中等
leetcode
Neteen7 小时前
【数据结构-思维导图】第二章:线性表
数据结构·c++·算法