C语言 | Leetcode C语言题解之第445题两数相加II

题目:

题解:

cpp 复制代码
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
    int stack1[100];
    int stack2[100];
    int top1 = 0;
    int top2 = 0;
    int carry = 0;
    int sum = 0;
    struct ListNode* temp = NULL;
    struct ListNode* head = NULL;
    while (l1) {
        stack1[top1++] = l1->val;
        l1 = l1->next;
    }
    while (l2) {
        stack2[top2++] = l2->val;
        l2 = l2->next;
    }
    while (top1 || top2 || carry) {
        int m = top1 > 0 ? stack1[--top1] : 0;
        int n = top2 > 0 ? stack2[--top2] : 0;
        sum = m + n + carry;
        carry = sum / 10;
        head = malloc(sizeof(struct ListNode));
        head->val = sum % 10;
        head->next = temp;
        temp = head;
    }
    return head;
}
相关推荐
左手の明天31 分钟前
SLIP 协议封装与解析详解:原理、C 代码与实战案例
linux·c语言·开发语言·c++
小灰灰搞电子2 小时前
C语言 <ctype.h> 头文件详解
c语言·ctype.h
阿钱真强道3 小时前
17 嵌入式操作系统 | uloop 事件循环:TCP 客户端
c语言·tcp/ip·tcp·事件循环·uloop
lvwangshu4 小时前
T2 最长上升子序列(lis)题解
动态规划·题解·技巧·性质题·思维好题
会员果汁5 小时前
函数调用和变长参数
c语言
lvwangshu5 小时前
T1 称重(weight)题解
题解·贪心·总结·技巧·性质题·思维好题
蛋蛋的就会顺顺的6 小时前
hot100——矩阵
java·数据结构·算法·leetcode·力扣
白山编程大哥8 小时前
Lua 中使用 C 语言的用户自定义类型——userdata
c语言·junit·lua
无敌贵点大王8 小时前
RTThread学习记录13——关于要使用一个外设,RTThread与cubemx到底要怎么配合?
c语言·stm32·学习·rtthread
phltxy8 小时前
C 语言动态内存管理:从申请空间到安全释放
c语言·开发语言·ui