Leetcode #2 Add Two Numbers C++

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

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

Output: 7 -> 0 -> 8

Explanation: 342 465 = 807.

这一下就考到了我上学期才学的数据结构,刚好线性表也是学得一塌糊涂。只记得有一个结点ListNode,ListNode里面重要的是有一个next指向下一个ListNode,然后还可以自定义一些其他的数据域。


注释里面给出了单链表结点的定义:

struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
};

结点带了一个值value和指向下一个结点的指针next,然后构造函数的唯一参数传值x给value,一个基本的定义。


大概了解了ListNode就好做了,下面是代码:

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *res=new ListNode(-1);
        ListNode *cur=res;
        int carry=0;
        while(l1||l2){
            int n1=l1?l1->val:0;
            int n2=l2?l2->val:0;
            int sum=n1+n2+carry;
            carry=sum/10;
            cur->next=new ListNode(sum%10);
            cur=cur->next;
            if(l1)
                l1=l1->next;
            if(l2)
                l2=l2->next;
        }
        if(carry)
            cur->next=new ListNode(1);
        return res->next;
    }
};

思路是:

  1. 首先,设一个carry来表示某位上两数字和大于9时需要进位1,初始值为0。
  2. 然后,只要两个数的结点上的数字不同时为0,就一直循环读数,从最低位开始遍历两个单链表的结点读取数字,如果为0,则由题可知这个数就是0,之后也就不需要再读这个单链表的后面结点的了;如果不为0就赋给n,再两个n和进位carry相加得到某位上的数字和。
  3. 接着,和除以10判断是否进位,>=10就是1,否则为0。
  4. 同时,和膜10来得到相加后该位上的数字,并新建结点附在现在所在结点current的后面。
  5. 在完成一次循环前,移动三个链表,切记先建立好next,再把current指向next
  6. 最后,在返回结果result的next指针之前,不要忘记判断carry还有没有值是否需要进位。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值