问题描述
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),那么只需要在后一位的计算时加上进位即可。当相加的两个元素位数不同时,补零代替。
C++实现
class sloution{
public:
ListNode * TwoNumberPluss(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;
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;
}
}