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;
}
相关推荐
Nazarick1 小时前
力扣LeetCode热题75题(1)
java·算法·leetcode·力扣
16月6日-晴2 小时前
斐波那契数列题解
算法·leetcode
烟烟Abandon2 小时前
FFmpeg开发基础之 C 语言编译器
c语言·开发语言·ffmpeg
郝学胜-神的一滴2 小时前
Effective Python 条款47:吃透惰性属性
大数据·开发语言·数据库·人工智能·python·算法·oracle
Zwawa3 小时前
断电后参数为什么全没了:把小车配置安全地存进 Flash
c语言·单片机·嵌入式
Keven_113 小时前
算法札记:有限差分
算法
忙里偷闲学python3 小时前
GK2A 林火蔓延预报算法说明
算法
我是伪码农4 小时前
11.21程序设计
数据结构·算法
Tisfy4 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
战6174 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法