(牛客网)链表相加(二)

简介: 假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。


嗯哼~



题目

描述

假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。


给定两个这种链表,请生成代表两个整数相加值的结果链表。


数据范围:0 ≤ n,m ≤ 1000000,链表任意值 0 ≤ val ≤ 9

要求:空间复杂度 O(n),时间复杂度 O(n)


示例



思路

单链表的翻转详细讲解:反转一个单链表(<---点击可看详解)



题解代码

struct ListNode* ReverseList(struct ListNode* pHead)
{
    // write code here
    struct ListNode* cur = pHead;
    struct ListNode* pre = NULL;
    while (cur != NULL)
    {
        struct ListNode* temp = cur->next;
        cur->next = pre;
        pre = cur;
        cur = temp;
    }
    return pre;
}
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2)
{
    // write code here
    head1 = ReverseList(head1);
    head2 = ReverseList(head2);
    int temp = 0;
    int add = 0;
    struct ListNode* newhead = NULL;
    while (head1 && head2)
    {
        temp = (head1->val + head2->val + add);
        if (temp >= 10)
        {
            add = 1;
            temp %= 10;
        }
        else
        {
            add = 0;
        }
        struct ListNode* cur = (struct ListNode*)malloc(sizeof(struct ListNode));
        cur->val = temp;
        cur->next = newhead;
        newhead = cur;
        head1 = head1->next;
        head2 = head2->next;
    }
    struct ListNode* empty = head1;
    struct ListNode* nonempty = head2;
    if (head1 != NULL)
    {
        empty = head2;
        nonempty = head1;
    }
    while (nonempty)
    {
        temp = (nonempty->val + add);
        if (temp >= 10)
        {
            add = 1;
            temp %= 10;
        }
        else
        {
            add = 0;
        }
        struct ListNode* cur = (struct ListNode*)malloc(sizeof(struct ListNode));
        cur->val = temp;
        cur->next = newhead;
        newhead = cur;
        nonempty = nonempty->next;
    }
    if (add == 1)
    {
        struct ListNode* cur = (struct ListNode*)malloc(sizeof(struct ListNode));
        cur->val = 1;
        cur->next = newhead;
        newhead = cur;
    }
    return newhead;
}


目录
相关文章
|
9月前
|
索引
【力扣刷题】两数求和、移动零、相交链表、反转链表
【力扣刷题】两数求和、移动零、相交链表、反转链表
62 2
【力扣刷题】两数求和、移动零、相交链表、反转链表
|
存储 索引
【Leetcode -141.环形链表 -2.两数相加】
【Leetcode -141.环形链表 -2.两数相加】
33 0
|
9月前
|
存储 算法 索引
【力扣刷题】只出现一次的数字、多数元素、环形链表 II、两数相加
【力扣刷题】只出现一次的数字、多数元素、环形链表 II、两数相加
64 1
|
9月前
|
索引
每日一题:力扣328. 奇偶链表
每日一题:力扣328. 奇偶链表
66 4
|
存储
数组实现链表(AcWing)
数组实现链表(AcWing)
92 0
|
9月前
每日一题——回文链表
每日一题——回文链表
|
9月前
【Leetcode 2807】在链表中插入最大公约数 ——链表|数论
链表插入的基础操作:每次在原链表的相邻两个节点中插入一个新的节点,新节点的值为相邻两个节点的最大公约数,最后返回新的链表即可
|
9月前
|
人工智能 Java
每日一题《剑指offer》数组篇之连续子数组的最大和
每日一题《剑指offer》数组篇之连续子数组的最大和
68 0
每日一题《剑指offer》数组篇之连续子数组的最大和
|
9月前
|
Java
每日一题《剑指offer》数组篇之数组中的逆序对
每日一题《剑指offer》数组篇之数组中的逆序对
45 0
每日一题《剑指offer》数组篇之数组中的逆序对
|
9月前
|
存储 人工智能 Java
每日一题《剑指offer》数组篇之构建乘积数组
每日一题《剑指offer》数组篇之构建乘积数组
51 0
每日一题《剑指offer》数组篇之构建乘积数组