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;
}
相关推荐
总爱写点小BUG1 小时前
打印不同的三角形(C语言)
java·c语言·算法
yaoh.wang1 小时前
力扣(LeetCode) 27: 移除元素 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·双指针
F_D_Z2 小时前
最长连续序列(Longest Consecutive Sequence)
数据结构·算法·leetcode
flashlight_hi3 小时前
LeetCode 分类刷题:199. 二叉树的右视图
javascript·算法·leetcode
LYFlied3 小时前
【每日算法】LeetCode 46. 全排列
前端·算法·leetcode·面试·职场和发展
LYFlied5 小时前
【每日算法】131. 分割回文串
前端·数据结构·算法·leetcode·面试·职场和发展
长安er5 小时前
LeetCode 300/152/416/32 动态规划进阶题型总结(最长递增子序列→最长有效括号)
数据结构·算法·leetcode·动态规划·剪枝
季远迩5 小时前
LeetCode 热题 100 Python3易懂题解(更新中)
算法·leetcode·哈希算法
xie_pin_an6 小时前
C 语言排序算法全解析:从原理到实战,附性能对比
c语言·算法·排序算法
Dream it possible!6 小时前
LeetCode 面试经典 150_回溯_组合(99_77_C++_中等)
c++·leetcode·面试·回溯