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。