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

运行结果


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

相关推荐
瓦力wow1 分钟前
c语言 写一个五子棋
c语言·c++·算法
时光飞逝的日子2 分钟前
Ubuntu 18.04设置静态IP的方法(图形化操作)
linux·ubuntu·静态ip
带鱼吃猫33 分钟前
Linux系统:ext2文件系统的核心概念和结构
linux·运维·服务器
qwer5558839 分钟前
linux-----------------库制作与原理(下)
linux·运维·服务器
m0_5195231042 分钟前
Linux——UDP/TCP协议理论
linux·tcp/ip·udp
hjjdebug1 小时前
c/c++数据类型转换.
c语言·c++·数据类型变换
花火QWQ1 小时前
图论模板(部分)
c语言·数据结构·c++·算法·图论
xmweisi021 小时前
【Linux】ssh命令 – 安全的远程连接服务
linux·安全·ssh
Pacify_The_North1 小时前
【进程控制二】进程替换和bash解释器
linux·c语言·开发语言·算法·ubuntu·centos·bash
ephemerals__1 小时前
【Linux】简易版Shell实现(附源码)
linux·运维·chrome