2.两数相加 | 链表

题目:给你两个非空的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储一位数字。请你将两个数相加,并以相同形式返回一个表示和的链表。你可以假设除了数字 0 之外,这两个数都不会以 0 开头。

**示例**

算法:迭代O(n)—>两链表的数字对应相加。 

 

 class Solution {
public:
    struct ListNode {
        int val;
        ListNode* next;
        ListNode() : val(0), next(nullptr) {}
        ListNode(int x) : val(x), next(nullptr) {}
        ListNode(int x, ListNode* next) : val(x), next(next) {}
    };
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        if (l1 == nullptr && l2 == nullptr) return nullptr;
        ListNode* dummy = new ListNode(0);//虚拟头结点,方便找到新链表
        ListNode* cur = dummy;//链接 新链表的指针
        int sum = 0;//两链表对应结点相加的和
        int carry = 0;//进位数(10为进制)
        while (l1 != NULL || l2 != NULL)
        {
            int x = l1 != NULL ? l1->val : 0;//两整数相加,如果较短的链表到达NULL,则结点值为0与另一链表结点相加
            int y = l2 != NULL ? l2->val : 0;
            sum = x + y + carry;
            if (sum >= 10)
            {
                carry = 1;//计算进位,大于十则进一位
            }
            else
            {
                carry = 0;
            }
            l1 = l1 != NULL ? l1->next : NULL;
            l2 = l2 != NULL ? l2->next : NULL;
            cur->next = new ListNode(sum % 10);//结点值为0 <= Node.val <= 9`,大于十则进一位
            cur = cur->next;
        }
        if (carry == 1)//最高位相加大于十,还需进位  99+9=801
        {
            cur->next = new ListNode(1);
            cur = cur->next;
        }
        cur->next=nullptr;//给新链表最后一个结点的next域添加NULL
        return dummy->next;
    }
};

int main()
{
    Solution s;
    //l1链表:2->4->3
    struct Solution::ListNode* a = new struct Solution::ListNode(3);
    struct Solution::ListNode* b = new struct Solution::ListNode(4, a);
    struct Solution::ListNode* l1 = new struct Solution::ListNode(2, b);
    //l2链表:5->6->4
    struct Solution::ListNode* c = new struct Solution::ListNode(4);
    struct Solution::ListNode* d = new struct Solution::ListNode(6, c);
    struct Solution::ListNode* l2 = new struct Solution::ListNode(5, d);
    struct Solution::ListNode* p = s.addTwoNumbers(l1, l2);
    for (; p != NULL; p = p->next)
    {
        if (p->next == NULL)
        {
            cout << p->val;
            break;
        }
        else
        {
            cout << p->val << "->";
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

宠宠熊

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值