Problem:
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Subscribe to see which companies asked this question
This problem shows the some fundamental operations of linked-lists. We list them as follows:
1. For most of cases, I prefer to define a new head so that it is easy to return the value. Then, the basic procedure to solve similar questions is to move the updated node of some original list to the newly created list.
2. When to add new nodes to a newly list, we need two pointers: one for the new list head and the other one is to indicate the tail of the list. When the two pointers are same (they are all NULL), it means that the new list is empty. At this time, we should update the two pointers to the same node. Otherwise, we should first update the next pointer of the tail node and slip it to its next node.
3. Usually, we always set the next pointer of the tail node to be NULL for the sake of safety.
4. For this problem, the addition may need to create a new node next to the tail node of the new list.
Sample code:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
ListNode *p_sum = NULL;
ListNode *p_cur = NULL;
bool overflow = false;
while(l1 != NULL && l2 != NULL) {
l1->val += l2->val + (overflow ? 1 : 0);
if(p_cur == NULL) {
p_sum = l1;
p_cur = l1;
} else {
p_cur->next = l1;
p_cur = p_cur->next;
}
l1 = l1->next;
l2 = l2->next;
p_cur->next = NULL;
overflow = (p_cur->val >= 10);
p_cur->val %= 10;
}
ListNode *p_unfinished = (l1 == NULL ? l2 : l1);
if(p_unfinished == NULL && overflow) {
p_cur->next = new ListNode(1);
} else if(p_unfinished) {
while(p_unfinished) {
if(!overflow) {
p_cur->next = p_unfinished;
break;
}
p_unfinished->val += (overflow ? 1 : 0);
overflow = (p_unfinished->val >= 10);
p_unfinished->val %= 10;
p_cur->next = p_unfinished;
p_unfinished = p_unfinished->next;
p_cur = p_cur->next;
p_cur->next;
}
if(overflow)
p_cur->next = new ListNode(1);
}
return p_sum;
}