Created
May 13, 2018 07:57
-
-
Save tratitude/48980cc0b88aad2730650db8bab603c2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) { | |
vector<int> sum; | |
int i; | |
int hold = 0; | |
for (i = 0; (l1 != NULL) || (l2 != NULL); i++) | |
{ | |
sum.push_back(hold); | |
if (l1 != NULL) | |
{ | |
sum[i] += l1->val; | |
l1 = l1->next; | |
} | |
if (l2 != NULL) | |
{ | |
sum[i] += l2->val; | |
l2 = l2->next; | |
} | |
hold = (int)sum[i] / 10; | |
if(hold) | |
sum[i] %= 10; | |
} | |
if(hold) | |
sum.push_back(hold); | |
ListNode *root = new ListNode(0); | |
ListNode *ptr; | |
ptr = root; | |
for (i = 0; i < sum.size(); i++) | |
{ | |
ptr->next = new ListNode(sum[i]); | |
ptr = ptr->next; | |
} | |
ptr = root->next; | |
delete root; | |
return ptr; | |
} | |
};L |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
sum.push_back(hold); // line17 run time error when use sum[i] = hold;