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;
}
相关推荐
千金裘换酒21 分钟前
LeetCode 移动零元素 快慢指针
算法·leetcode·职场和发展
iuu_star1 小时前
C语言数据结构-顺序查找、折半查找
c语言·数据结构·算法
漫随流水2 小时前
leetcode算法(515.在每个树行中找最大值)
数据结构·算法·leetcode·二叉树
千金裘换酒4 小时前
LeetCode反转链表
算法·leetcode·链表
JoyCheung-4 小时前
Free底层是怎么释放内存的
linux·c语言
圣保罗的大教堂5 小时前
leetcode 1161. 最大层内元素和 中等
leetcode
闲看云起6 小时前
LeetCode-day6:接雨水
算法·leetcode·职场和发展
黛色正浓6 小时前
leetCode-热题100-贪心合集(JavaScript)
javascript·算法·leetcode
一起努力啊~7 小时前
算法刷题--长度最小的子数组
开发语言·数据结构·算法·leetcode