/**
* 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* root = new ListNode(0);
add(l1, l2, root, 0);
return root->next;
}
void add(ListNode *l1, ListNode *l2, ListNode* pre, int carry) {
if (l1 == NULL) addSingle(l2, pre, carry);
else if (l2 == NULL) addSingle(l1, pre, carry);
else {
int num = l1->val + l2->val + carry;
pre->next = new ListNode(num % 10);
add(l1->next, l2->next, pre->next, num/10);
}
}
void addSingle(ListNode* n, ListNode* pre, int carry) {
if (n == NULL) {
if (carry == 0 ) return;
else {
pre->next = new ListNode(carry);
return;
}
}
int num = carry + n->val;
pre->next = new ListNode(num % 10);
addSingle(n->next, pre->next, num/10);
}
};
No comments:
Post a Comment