2.5 You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
FOLLOW UP
Suppose the digits are stored in forward order. Repeat the above problem.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
Iterative:
ListNode* addLists(ListNode *l1, ListNode *l2) {
int value = 0;
int carry = 0;
ListNode *ret = new ListNode(0);
ListNode *l = ret;
while (l1 && l2) {
value = l1->val + l2->val + carry;
carry /= 10;
l->next = new ListNode(value%10);
l = l->next;
l1 = l1->next;
l2 = l2->next;
}
while (l1) {
value = l1->val + carry;
carry /= 10;
l->next = new ListNode(value%10);
l = l->next;
l1 = l1->next;
}
while (l2) {
value = l2->val + carry;
carry /= 10;
l->next = new ListNode(value%10);
l = l->next;
l2 = l2->next;
}
if (carry) {
l->next = new ListNode(carry);
}
l = ret;
ret = ret->next;
delete l;
return ret;
}
Recursive:
ListNode* addLists(ListNode *l1, ListNode *l2, int carry) {
if (l1 == NULL && l2 == NULL && carry == 0) {
return NULL;
}
ListNode *result = new ListNode(0);
int value = carry;
if (l1) {
value += l1->val;
}
if (l2) {
value += l2->val;
}
result->val = value % 10;
if (l1 || l2 || value >= 10) {
result->next = addLists(l1 ? l1->next : NULL, l2 ? l2->next : NULL, value/10);
}
return result;
}
FOLLOW UP
struct PartialSum {
ListNode *sum;
int carry;
PartialSum() : sum(NULL), carry(0) {}
};
int getLength(ListNode *head) {
int len = 0;
while (head) {
head = head->next;
len++;
}
return len;
}
ListNode* padList(ListNode *head, int padding) {
for (int i = 0; i < padding; i++) {
ListNode *n = new ListNode(0);
n->next = head;
head = n;
}
return head;
}
ListNode* insertBefore(ListNode *l, int value) {
ListNode *n = new ListNode(value);
n->next = l;
return n;
}
PartialSum addListsHelper(ListNode *l1, ListNode *l2) {
if (l1 == NULL && l2 == NULL) {
PartialSum sum;
return sum;
}
PartialSum sum = addListsHelper(l1->next, l2->next);
int value = sum.carry + l1->val + l2->val;
sum.sum = insertBefore(sum.sum, value%10);
sum.carry = value / 10;
return sum;
}
ListNode* addLists(ListNode *l1, ListNode *l2) {
int len1 = getLength(l1);
int len2 = getLength(l2);
if (len1 < len2) {
l1 = padList(l1, len2-len1);
} else {
l2 = padList(l2, len1-len2);
}
PartialSum sum = addListsHelper(l1, l2);
if (sum.carry == 0) {
return sum.sum;
} else {
return insertBefore(sum.sum, sum.carry);
}
}