LeetCode2. Add Two Numbers
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.
解析:
给定两个逆序的链表,链表中的数值是非负的,每个链表分别代表一个数字,计算这两个链表代表数字之和,并将此数字输出为链表的形式。
如l1=(2 -> 4 -> 3)代表数字342,l2=(5 -> 6 -> 4),代表数字465.342+465=807.最终输出的链表为7 -> 0 -> 8
解析:
遍历两个链表,将对应位置数值相加,处理进位的情况,建立一个新链表,将和作为数值,添加一个新节点到新链表后面。还有就是最高位的进位问题要最后特殊处理一下。
具体代码如下:
[cc lang=”C++”]
/**
* 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* node = new ListNode(0);
ListNode* p1 = l1;
ListNode* p2 = l2;
ListNode* p3 = node;
int carry = 0;
while(p1!=NULL || p2 != NULL)
{
if(p1 != NULL)
{
carry += p1->val;
p1 = p1->next;
}
if(p2 != NULL)
{
carry += p2->val;
p2 = p2->next;
}
p3->next = new ListNode(carry%10);//处理进位
p3 = p3->next;
carry /= 10;
}
if(carry==1)
p3->next=new ListNode(1);//最高位有进位,特殊处理
return node->next;
}
};
[/cc]
运行结果:

参考:
http://wiki.jikexueyuan.com/project/leetcode-book/01.html
https://www.jiuzhang.com/solution/add-two-numbers/