/**
* 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* ret = NULL;
ListNode* ptr1 = l1;
ListNode* ptr2 = l2;
ListNode* ptr3 = ret;
int temp = 0;
while(ptr1 || ptr2)
{
int val1 = 0;
int val2 = 0;
if(ptr1)
val1 = ptr1->val;
if(ptr2)
val2 = ptr2->val;
int sum = val1 + val2 + temp;
ListNode* node = new ListNode(sum % 10);
cout << sum % 10;
temp = (int)(sum / 10);
if(ptr3)
{
ptr3->next = node;
ptr3 = ptr3->next;
}
else
{
ret = node;
ptr3 = ret;
}
if(ptr1)
ptr1 = ptr1->next;
if(ptr2)
ptr2 = ptr2->next;
}
if(temp > 0)
ptr3->next = new ListNode(temp);
return ret;
}
};
leet code 2. 两数相加
最新推荐文章于 2020-07-03 00:33:06 发布