Leetcode—剑指Offer LCR 025.两数相加II【中等】

2023每日刷题(六十七)

Leetcode---LCR 025.两数相加II

实现代码

c 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
    struct ListNode* head1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    head1->next = NULL;
    struct ListNode* head2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    head2->next = NULL;
    struct ListNode* p, *q, *p2, *q2;
    p = l1;
    p2 = l1->next;
    q = l2;
    q2 = l2->next;
    // 链表翻转
    while(p != NULL) {
        p->next = head1->next;
        head1->next = p;
        p = p2;
        if(p2 == NULL) {
            break;
        }
        p2 = p2->next;
        
    }
    while(q != NULL) {
        q->next = head2->next;
        head2->next = q;
        q = q2;
        if(q2 == NULL) {
            break;
        }
        q2 = q2->next;
        
    }
    p = head1->next;
    q = head2->next;
    head1->next = NULL;
    int c = 0;
    while(p && q) {
        struct ListNode* s = (struct ListNode*)malloc(sizeof(struct ListNode));
        s->next = NULL;
        int sum = p->val + q->val + c;
        c = sum / 10;
        s->val = sum % 10;
        s->next = head1->next;
        head1->next = s;
        p = p->next;
        q = q->next;
    }
    while(p != NULL) {
        struct ListNode* s = (struct ListNode*)malloc(sizeof(struct ListNode));
        s->next = NULL;
        int sum = p->val + c;
        c = sum / 10;
        s->val = sum % 10;
        s->next = head1->next;
        head1->next = s;
        p = p->next;
    }
    while(q != NULL) {
        struct ListNode* s = (struct ListNode*)malloc(sizeof(struct ListNode));
        s->next = NULL;
        int sum = q->val + c;
        c = sum / 10;
        s->val = sum % 10;
        s->next = head1->next;
        head1->next = s;
        q = q->next;
    }
    if(c) {
        struct ListNode* s = (struct ListNode*)malloc(sizeof(struct ListNode));
        s->next = NULL;
        s->val = c;
        s->next = head1->next;
        head1->next = s;
    }
    return head1->next;
}

运行结果


之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
Janspran1 小时前
监控系统4 - LVGL | sqlite3 | mqtt
linux·sqlite3·嵌入式实时数据库
敲上瘾1 小时前
Docker镜像构建指南:Dockerfile语法与docker build命令全解析
linux·服务器·docker·微服务·容器
@小博的博客5 小时前
【Linux探索学习】第二篇Linux的基本指令(2)——开启Linux学习第二篇
linux·运维·学习
Kiri霧6 小时前
Rust模式匹配详解
开发语言·windows·rust
openHiTLS密码开源社区7 小时前
【密码学实战】openHiTLS passwd命令行:专业密码哈希生成工具
linux·密码学·哈希算法·ldap·密码策略·随机盐值
WTCLLB8 小时前
netgear r6220 路由器,刷openwrt后,系统备份还原
linux·网络·智能路由器·openwrt
程序设计实验室8 小时前
使用命令行删除 Windows 网络映射驱动器
windows
很㗊8 小时前
C与C++---类型转换
c语言·开发语言
say_fall8 小时前
精通C语言(3. 自定义类型:联合体和枚举)
c语言·开发语言
迎風吹頭髮9 小时前
UNIX下C语言编程与实践38-UNIX 信号操作:signal 函数与信号捕获函数的编写
linux·c语言·unix