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;
}
相关推荐
墨染点香3 分钟前
LeetCode 刷题【124. 二叉树中的最大路径和、125. 验证回文串】
算法·leetcode·职场和发展
dllxhcjla1 小时前
07 标识符命名规则
c语言
2201_758875442 小时前
LeetCode:19. 删除链表的倒数第 N 个结点
算法·leetcode·链表
Wenhao.2 小时前
LeetCode 合并K个升序链表
leetcode·链表·golang
杨福瑞2 小时前
C语言数据结构:算法复杂度(2)
c语言·开发语言·数据结构
DuHz2 小时前
C程序中的循环语句
c语言·嵌入式硬件·软件工程
一念&3 小时前
每日一个C语言知识:C 指针
c语言·开发语言
薰衣草23333 小时前
hot100练习-11
算法·leetcode
Q741_1474 小时前
C++ 面试基础考点 模拟题 力扣 38. 外观数列 题解 每日一题
c++·算法·leetcode·面试·模拟
deng-c-f4 小时前
Linux C/C++ 学习日记(22):Reactor模式(二):实现简易的webserver(响应http请求)
linux·c语言·网络编程·reactor·http_server