add-two-numbers(LeetCode)

原题来自牛客网LeetCode:链接

给定两个代表非负数的链表,数字在链表中是反向存储的(链表头结点处的数字是个位数,第二个结点上的数字是十位数…),求这个两个数的和,结果也用链表表示。

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)

输出: 7 -> 0 -> 8

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

示例1

输入
{0},{0}

输出
{0}

示例2

输入
{0},{1}

输出
{1}

思路

数字已经是反向存储了,因此逐位相加然后进位即可,用一个变量out记录是否有进位。

用尾插法添加每一个结点即可,开头第一个结点可以设为0方便尾插,最后返回head->next即可。

代码如下:

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        if(!l1&&!l2)
            return NULL;
        ListNode *ans,*p=NULL;
        int out=0,num,sum=0;
        p=new ListNode(0);
        ans=p;
        while(l1||l2||out){
            sum=0;
            if(l1){
                sum+=l1->val;
                l1=l1->next;
            }
            if(l2){
                sum+=l2->val;
                l2=l2->next;
            }
            if(out)
                sum+=1;
            out=(sum>=10? 1:0);
            num=sum%10;
            ListNode *tmp=new ListNode(num);
            p->next=tmp;
            p=tmp;
        }
        return ans->next;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值