/**
* 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)
{
ListNode* newHead = new ListNode(-1);
ListNode* tail = newHead;
int carry = 0;
int val = 0;
while(l1 != NULL || l2 != NULL)
{
if(l1 != NULL && l2 != NULL)
{
int temp = l1->val + l2->val + carry;
val = temp%10;
carry = temp/10;
}
else
{
int temp = ( (l1 != NULL)?l1->val:l2->val ) + carry;
val = temp%10;
carry = temp/10;
}
ListNode* node = new ListNode(val);
tail->next = node;
tail = node;
l1 = (l1 != NULL)? l1->next:NULL;
l2 = (l2 != NULL)? l2->next:NULL;
}
if (carry)
{
ListNode* node = new ListNode(1);
tail->next = node;
}
return newHead->next;
}
};
Add Two Numbers
最新推荐文章于 2021-02-19 08:37:33 发布