Skip to content

Instantly share code, notes, and snippets.

Created March 28, 2013 09:56
Show Gist options
  • Save anonymous/5262065 to your computer and use it in GitHub Desktop.
Save anonymous/5262065 to your computer and use it in GitHub Desktop.
/*
http://leetcode.com/onlinejudge#question_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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode* tl = new ListNode(-1);
ListNode* ans = tl;
tl->next = NULL;
int sum = 0,
cry = 0;
bool firstnum = true;
while (l1 || l2)
{
sum = cry;
if (l1)
{
sum += l1->val;
l1 = l1->next;
}
if (l2)
{
sum += l2->val;
l2 = l2->next;
}
cry = sum / 10;
sum = sum % 10;
/* first num*/
if (firstnum)
{
tl->val = sum;
firstnum = false;
}
else
{
ListNode* tmp = new ListNode(sum);
tl->next= tmp;
tl = tmp;
}
}
/* last cry */
if (cry)
{
ListNode* tmp = new ListNode(cry);
tmp->next = NULL;
tl->next = tmp;
}
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment