Q: numbers are stored in reverse order.
L1: 7->1->6 (716)
L2:5->9->2 (295)
L1 + L2 = 716 + 295 = 912
L3: 2->1->9.
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2{
ListNode* newHead = new ListNode(-1);
ListNode* p = newHead;
int carry = 0;
while(l1 || l2 || carry){
int sum = (l1? l1->val : 0) + (l2? l2->val : 0) + carry;
p->next = new ListNode(sum%10);
carry = sum/10;
p = p->next;
l1 ? l1=l1->next : 0;
l2 ? l2=l2->next : 0;
}
return newHead->next;
}
Follow up: what if numbers are stored in forward order?
Eg: (1->2->3->4) + (5->6->7)
Now the problem becomes a little bit more cumbersome. Firstly, if they have different length, we have to add zeroes in front of shorter list. Secondly, we have to find the carry from the last two sum. Following code solve this problem recursively.
void insertFront(ListNode* &head, int value){
ListNode* newHead = new ListNode(value);
newHead->next = head;
head = newHead;
}
void addZeroes(ListNode* &head, int len){
for (int i = 0; i<len; ++i) {
insertFront(head, 0);
}
}
int length(ListNode* head){
int len = 0;
while(head){
++len;
head = head->next;
}
return len;
}
ListNode* helper(ListNode* l1, ListNode* l2, int& carry){
if(!l1 && !l2 && !carry) return nullptr;
ListNode* res = helper(l1? l1->next : nullptr, l2 ? l2->next : nullptr, carry);
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
insertFront(res, sum % 10);
carry = sum/10;
return res;
}
ListNode* addTwoNumbers2(ListNode* l1, ListNode* l2){
int len1 = length(l1), len2 = length(l2);
(len1 < len2) ? addZeroes(l1, len2 - len1) : addZeroes(l2, len1 - len2);
int carry = 0;
ListNode* l3 = helper(l1, l2, carry);
if (carry) insertFront(l3, carry);
return l3;
}
For testing:
int main(int argc, const char * argv[]) {
// insert code here...
ListNode* list1 = nullptr;
ListNode* list2 = nullptr;
cout << "list stored in forward order: \n";
//Node * listx = nullptr;
insertFront(list1, 4);
insertFront(list1, 3);
insertFront(list1, 2);
insertFront(list1, 9);
cout << "List1: ";
printList(list1);
insertFront(list2, 9);
insertFront(list2, 9);
insertFront(list2, 8);
cout << "List2: ";
printList(list2);
ListNode* list3 = addTwoNumbers2(list1, list2);
cout << "Adding two above lists\n";
cout << "List3: ";
printList(list3);
return 0;
}