Add Two Numbers
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
class Solution {
public:
ListNode* addTwoNumbers(ListNode *l1, ListNode *l2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode *head = new ListNode(0);
ListNode *cur = head;
int add = 0;
//print(head);
//cout<<"the result"<<endl;
while ( l1 != NULL || l2 != NULL || add == 1)
{
if (add == 1)
{
cur->val = 1;
add = 0;
}
if ( l1 !=NULL && l2 == NULL)
{
//cout<<"in case 1"<<endl;
if(cur->val + l1->val > 9)
add = 1;
cur->val = (cur->val + l1->val)%10;
//l1 = l1->next;
}
else if ( l1 == NULL && l2 != NULL)
{
if(cur->val + l2->val > 9)
add = 1;
cur->val = (cur->val + l2->val)%10;
//l2 = l2->next;
//cout<<"cur value:"<<cur->val<<endl;
}
if ( l1 == NULL && l2 == NULL && add == 1 )
{
cur->val = 1;
}
if ( l1 != NULL && l2 != NULL)
{
//cout<<"in case 3"<<endl;
if( cur->val + l1->val + l2->val > 9)
add = 1;
cur->val = (cur->val + l1->val + l2->val)%10;
//l1 = l1->next;
//l2 = l2->next;
}
if(l1 == NULL || l1->next == NULL)
l1 = NULL;
else
l1 = l1->next;
if(l2 == NULL || l2->next == NULL)
l2 = NULL;
else
l2 = l2->next;
//cout<<"cur value:"<<cur->val<<endl;
if(l1 != NULL || l2 != NULL || add == 1)
{
cur->next = new ListNode(0);
cur = cur->next;
}
//print(head);
}
cur->next = NULL;
// print(head);
return head;
}
};
Redo this problem in 2014
class Solution {
public:
ListNode* addTwoNumbers(ListNode *l1, ListNode *l2)
{
ListNode* head = new ListNode(-1);
ListNode* pre = head;
int add = 0;
while(l1 != NULL || l2 != NULL)
{
int v1 = 0;
int v2 = 0;
if(l1 == NULL)
v1 = 0;
else
{
v1 = l1->val;
l1 = l1->next;
}
if(l2 == NULL)
v2 = 0;
else
{
v2 = l2->val;
l2 = l2->next;
}
ListNode* next = new ListNode((v1 + v2 + add) % 10);
add = (v1 + v2 + add)/10;
pre->next = next;
pre = pre->next;
}
if(add == 1)
{
pre->next = new ListNode(1);
pre = pre -> next;
}
pre->next = NULL;
return head->next;
}
};
Round 2:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
if(l1 == NULL || l2 == NULL)
return l1 == NULL ? l2 : l1;
int carry = 0;
ListNode *iter1 = l1, *iter2 = l2, *pre1 = NULL;
while(iter1 != NULL)
{
int val1 = iter1->val;
int val2 = iter2 == NULL? 0 : iter2->val;
if(val1 + val2 + carry > 9)
{
iter1->val = (val1 + val2 + carry) % 10;
carry = 1;
}
else
{
iter1->val = val1 + val2 + carry;
carry = 0;
}
if(iter1->next == NULL && iter2)
{
iter1->next = iter2->next;
iter2->next = NULL;
}
pre1 = iter1;
iter1 = iter1->next;
iter2 = iter2 == NULL ? NULL : iter2->next;
}
if(carry == 1)
{
ListNode * newNode = new ListNode(1);
pre1->next = newNode;
}
return l1;
}
};