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

运行结果


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

相关推荐
闲晨11 分钟前
C++ 继承:代码传承的魔法棒,开启奇幻编程之旅
java·c语言·开发语言·c++·经验分享
2401_8504108334 分钟前
文件系统和日志管理
linux·运维·服务器
XMYX-01 小时前
使用 SSH 蜜罐提升安全性和记录攻击活动
linux·ssh
幼儿园老大*2 小时前
Go的环境搭建以及GoLand安装教程
开发语言·经验分享·后端·golang·go
考试宝2 小时前
国家宠物美容师职业技能等级评价(高级)理论考试题
经验分享·笔记·职场和发展·学习方法·业界资讯·宠物
弗锐土豆3 小时前
Windows系统中Oracle VM VirtualBox的安装
windows·虚拟机·virtualbox
秋の花3 小时前
【JAVA基础】Java集合基础
java·开发语言·windows
jrrz08283 小时前
LeetCode 热题100(七)【链表】(1)
数据结构·c++·算法·leetcode·链表
二十雨辰3 小时前
[linux]docker基础
linux·运维·docker
饮浊酒4 小时前
Linux操作系统 ------(3.文本编译器Vim)
linux·vim