Leetcode-Add Two Numbers

question:

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

C++solution:

给出两条链,每个节点包含一个int的值(val)和指向下一个节点的指针,最后一个节点的指针为NULL。

一般情况下,两条链表对应节点的val值相加得到输出链的节点的val。如例子:2 + 5 = 7。另外需要考虑的是满10进1,如例子:4 + 6 = 10,对10取模、取余,0保留在当前结点,1进入下一个节点的相加中,如例子:3 + 4 + 1 = 8。若其中一条链只有3个节点,另一条链有四个节点,依旧相加,无数可取即为0。若最后两个节点相加满10,增加新节点进1。

所以,一般情况下应是:l1.val + l2.val + carry = l3.val

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* result = new ListNode(0);//注意区别 list list* 
        ListNode *a = l1, *b = l2;
        ListNode* curr = result;
        int sum = 0;
        int carry = 0;
        
        while(a != NULL || b != NULL) {
        	if(a != NULL) {
        		sum = sum + a->val;
        		a = a->next;
        	}
        	if(b != NULL) {
        		sum = sum + b->val; 
        		b = b->next;
        	}
        	sum = sum + carry;
        	carry = sum /10;
        	ListNode* newNode = new ListNode(sum%10);
        	curr->next = newNode;
        	curr = newNode;
        	sum = 0;
        }
        if(carry != 0) {
        	ListNode* newNode = new ListNode(carry);
        	curr->next = newNode;
        }
        return result->next;
    }
}; 
以前写代码常用null,但在leetcode那边不能识别null,得用NULL。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值