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
Personal tips: 单链表。代码如下:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *l = new ListNode(0);
ListNode *r = l;
while (l1!=NULL||l2!=NULL)
{
ListNode *s = new ListNode(0);
int x = (l1 == NULL) ? 0 : l1->val;
int y = (l2 == NULL) ? 0 : l2->val;
s->next = r->next;
s->val = (x + y + r->val) / 10;
r->val = (x +y + r->val) % 10;
if (((l1!= NULL) ? l1->next : NULL )== NULL&& ((l2 != NULL) ? l2->next : NULL) == NULL&&s->val==0) { return l; }
r->next = s;
r = s;
l1 = (l1!= NULL) ? l1->next : NULL;
l2 = (l2!= NULL) ? l2->next : NULL;
}
return l;
}
};