You are given two linked lists representing two non-negative numbers. The digits are stored in order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
43 + 564 = 607
Input: (4 -> 3) + (5 -> 6 -> 4)
Output: 6 -> 0 -> 7
This one is different with the previous one , since the digits here are not stored in reverse order, the first node is the highest digits of a number. Since the length of these two linked list may not be equal, padding 0's should be added to the shorter list if their length are not equal.
Input: (4 -> 3) + (5 -> 6 -> 4)==== > (0->4 -> 3) + (5 -> 6 -> 4)
Output: 6 -> 0 -> 7
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
int len1 = length(l1);
int len2 = length(l2);
if(len1 < len2) addPaddingZeros(&l1, len2-len1);
if(len2 < len1) addPaddingZeros(&l2, len1-len2);
//std::cout << len1 << " and " << len2 << std::endl;
int carry = 0;
ListNode *head = addTwoNumbers(l1, l2, carry);
if(carry) {
ListNode *a_node = new ListNode(carry);
a_node->next = head;
head = a_node;
}
return head;
}
// here the llinked list l1 and l2 have the equal length.
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2, int &carry) {
if(l1 == NULL) return NULL;
ListNode *a_node = new ListNode(0);
a_node->next = addTwoNumbers(l1->next, l2->next, carry);
int temp = (l1->val + l2->val + carry) % 10;
carry = (l1->val + l2->val + carry) / 10;
a_node->val = temp;
return a_node;
}
int length(ListNode *head) {
if (head == NULL) return 0;
int len = 0;
while(head) {
++len;
head = head->next;
}
return len;
}
void addPaddingZeros(ListNode **head, int count) {
if(count == 0 || *head == NULL) return;
while(count) {
--count;
ListNode *dummy_node = new ListNode(0);
dummy_node->next = *head;
*head = dummy_node;
}
}
};