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;
}
相关推荐
郑州吴彦祖77211 分钟前
数据结构——二叉树经典习题讲解
java·数据结构·算法·leetcode
qy发大财15 分钟前
跳跃游戏II(力扣45)
算法·leetcode
Joyner201818 分钟前
python-leetcode-相交链表
算法·leetcode·链表
和光同尘@44 分钟前
74. 搜索二维矩阵(LeetCode 热题 100)
数据结构·c++·线性代数·算法·leetcode·职场和发展·矩阵
柠石榴1 小时前
【练习】【二分】力扣热题100 34. 在排序数组中查找元素的第一个和最后一个位置
c++·算法·leetcode·二分
Tisfy2 小时前
LeetCode 2209.用地毯覆盖后的最少白色砖块:记忆化搜索之——深度优先搜索(DFS)
算法·leetcode·深度优先·dfs·题解·记忆化搜索·深度优先搜索
我爱蛋蛋后2 小时前
Linux驱动开发之音频驱动与基础应用编程
linux·c语言·驱动开发·音视频
卷卷的小趴菜学编程3 小时前
c++之多态
c语言·开发语言·c++·面试·visual studio code
夏末秋也凉3 小时前
力扣-回溯-491 非递减子序列
数据结构·算法·leetcode
penguin_bark3 小时前
三、动规_子数组系列
算法·leetcode