Skip to content

Instantly share code, notes, and snippets.

@tratitude
Created May 13, 2018 07:57
Show Gist options
  • Save tratitude/48980cc0b88aad2730650db8bab603c2 to your computer and use it in GitHub Desktop.
Save tratitude/48980cc0b88aad2730650db8bab603c2 to your computer and use it in GitHub Desktop.
/**
* 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
@tratitude
Copy link
Author

sum.push_back(hold); // line17 run time error when use sum[i] = hold;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment