This is from the http://www.ihas1337code.com/onlinejudge website.  His onlinejudge testing is really neat. I’d like to setup something like that.

```// Definition for singly-linked list.
// DO NOT modify this.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
// NO #include's are required

bool bCarry = false;
ListNode *result = NULL, *tail = NULL;
int sum = 0;

while(true) {
// No more values so break out of loop and check carry
if (!l1 && !l2) {
if (bCarry) {
tail->next = new ListNode(1);
}
break;
}
// Values in list
if (l1 || l2) {
sum = 0;
// Check list 1
if (l1) {
sum += l1->val;
l1 = l1->next;
}
// Check list 2
if (l2) {
sum += l2->val;
l2 = l2->next;
}
if (bCarry) {
sum += 1;
bCarry = false;
}
if (!result)
result = tail = new ListNode(sum%10);
else {
tail->next = new ListNode(sum%10);
tail = tail->next;
}
// Calculate carry
bCarry = (sum >= 10) ? true : false;
}

}
return result ;

}```
This entry was posted in Coding and tagged , . Bookmark the permalink.