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

 嗯哼~



题目

描述

假设链表中每一个节点的值都在 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;

}


 个人主页:Lei宝啊

愿所有美好如期而遇

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lei宝啊

觉得博主写的有用就鼓励一下吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值