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;
}
相关推荐
C++ 老炮儿的技术栈13 小时前
MFC 自定义纯色居中文字进度条控件
c语言·数据库·c++·windows·算法·c·visual studio
tachibana213 小时前
hot100 排序链表(148)
java·数据结构·算法·leetcode·链表
不能跑的代码不是好代码13 小时前
二叉树从基础概念到LeetCode实战
算法·leetcode
凯瑟琳.奥古斯特14 小时前
二分查找解力扣1011最优运载能力
开发语言·c++·算法·leetcode·职场和发展
Drone_xjw1 天前
从 GDB 到 CDB:C/C++ 程序调试的两把“手术刀”
c语言·开发语言·c++
YuK.W1 天前
Leetcode100: 70.爬楼梯、118.杨辉三角、198.打家劫舍
java·算法·leetcode
旖-旎1 天前
《LeetCode 64 最小路径和 || LeetCode 174 地下城游戏》
c++·算法·leetcode·动态规划
gugucoding1 天前
25. 【C语言】二进制文件与随机读写
c语言·开发语言
凯瑟琳.奥古斯特1 天前
力扣1009补码解法C++实现
开发语言·c++·算法·leetcode·职场和发展
十月的皮皮1 天前
C语言学习笔记20260706-栈的压入、弹出序列验证
c语言·笔记·学习