Skip to content

Add 2 numbers

Course: Linked List - chapter 5

Q - https://leetcode.com/problems/add-two-numbers-ii/description/

1 approach can be reversing the linked list, then adding it and then reversing it back. Not going to discuss this as we already know how to reverse a linked list. Try writing the code for this approach.

Another way to solve it is, pad with 0’s at the front so that both of them are of equal size. Now go for a recursive solution. Why recursive? As we first need to add the rightmost elements and whatever carry over comes should be added to the previous digits and so on. So, we will only add the current nodes when the right side nodes (next nodes) are already processed. So first we should recurse for the next nodes, get the carry over returned and then add the current node.

pair<Node*, int> add(Node* first, Node* second) {
if (first == NULL) return {NULL, 0};
pair<Node*, int> nextDigit = add(first->next, second->next);
int curr_sum = first->data + second->data + nextDigit.second;
int curr_digit = curr_sum % 10;
int carry = curr_sum / 10;
Node *curr_node = new Node(curr_digit, nextDigit.first);
return {curr_node, carry};
}
pair<Node*, int> added = add(first, second);
Node* head = added.first;
if(added.second != 0) {
head = addNodeAtFront(head, added.second);
}
return head;