<pre name="code" class="cpp">
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *ans = new ListNode(-1);
ListNode *tail = ans;
int carry=0;
while (l1&&l2) {
int tmp=l1->val+l2->val+carry;
carry=tmp/10;
//尾插法插入。
tail->next=new ListNode(tmp%10);
tail=tail->next;
l1=l1->next;
l2=l2->next;
}
while (l1) {
int tmp=l1->val+carry;
carry=tmp/10;
tail->next=new ListNode(tmp%10);
tail=tail->next;
l1=l1->next;
}
while (l2) {
int tmp=l2->val+carry;
carry=tmp/10;
tail->next=new ListNode(tmp%10);
tail=tail->next;
l2=l2->next;
}
if (carry) {
tail->next=new ListNode(1);
tail=tail->next;
}
ans=ans->next;//去掉哨位节点
return ans;
}
};