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;
}

运行结果


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

相关推荐
Pandaconda8 分钟前
【计算机网络 - 基础问题】每日 3 题(十)
开发语言·经验分享·笔记·后端·计算机网络·面试·职场和发展
小立爱学习21 分钟前
Linux 给 vmlinux 添加符号
linux·c语言
Crossoads1 小时前
【数据结构】排序算法---基数排序
c语言·开发语言·数据结构·算法·排序算法
DieSnowK1 小时前
[项目][WebServer][CGI机制 && 设计]详细讲解
linux·开发语言·c++·http·项目·webserver·cgi机制
老薛爱吃大西瓜1 小时前
DAY15:链表实现学生信息管理系统
c语言·数据结构·学习·链表
guoguoqiang.1 小时前
我与Linux的爱恋:命令行参数|环境变量
linux·运维·服务器·c语言·学习
空白诗2 小时前
使用 nvm 管理 node 版本:如何在 macOS 和 Windows 上安装使用nvm
windows·macos·node.js·nvm
大耳朵土土垚2 小时前
【Linux 】开发利器:深度探索 Vim 编辑器的无限可能
linux·编辑器·vim
极客小张2 小时前
基于STM32MP157与OpenCV的嵌入式Linux人脸识别系统开发设计流程
linux·stm32·单片机·opencv·物联网
x66ccff2 小时前
【linux】4张卡,坏了1张,怎么办?
linux·运维·服务器