描述
【题解】
模拟高精度的加法。 用x来记录前面的进位就好。【代码】
/**
* 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 *h = new ListNode(0);
ListNode *t = h;
ListNode *p1,*p2;
p1 = l1,p2 = l2;
int x = 0;
while (p1 && p2){
t->val = (p1->val)+(p2->val)+x;
x = t->val/10;
t->val%=10;
p1=p1->next;p2 = p2->next;
if (p1&&p2) {
t->next = new ListNode(0);
}else break;
t=t->next;
}
if (p1==NULL) p1 = p2;
while (p1){
t->next = new ListNode(0);
t = t->next;
t->val = p1->val+x;
x = t->val/10;
t->val%=10;
p1 = p1->next;
}
if (x>0){
t->next = new ListNode(x);
}
return h;
}
};