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

运行结果


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

相关推荐
芯联智造2 小时前
【stm32简单外设篇】- WS2812单线地址式 RGB 灯带
c语言·stm32·单片机·嵌入式硬件
Wpa.wk3 小时前
Git日志+分支管理+基础冲突解决
经验分享·git·测试工具
Storynone3 小时前
【Day20】LeetCode:39. 组合总和,40. 组合总和II,131. 分割回文串
python·算法·leetcode
一瓢西湖水3 小时前
Windows安装OpenClaw实践指南
人工智能·windows·ai
V__KING__4 小时前
systemd-remount-fs,fstab之间的渊源
linux·服务器·网络
sjmaysee4 小时前
Windows操作系统部署Tomcat详细讲解
java·windows·tomcat
酿情师4 小时前
Windows Subsystem for Linux (WSL, Ubuntu)安装教程(详细)
linux·windows·ubuntu
Titan20245 小时前
Linux环境变量个人笔记
linux·服务器·c++
青柠代码录5 小时前
【Linux】路径区分:testdir、testdir/、testdir/*
linux·运维·服务器
7yewh5 小时前
jetson_yolo_deployment 02_linux_dev_skills
linux·python·嵌入式硬件·yolo·嵌入式