**
* 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
if (l1==NULL && l2==NULL)
return NULL;
ListNode *retHead = NULL;
ListNode **res=&retHead;
int carry = 0;
int value = 0;
while (l1!=NULL || l2!= NULL) {
value=0;
value +=carry;
if (l1!=NULL) {
value += l1->val;
l1=l1->next;
}
if (l2!=NULL) {
value += l2->val;
l2=l2->next;
}
carry = value/10;
value = value;
*res = new ListNode(value);
res = &(*res)->next;
}
if (carry >0)
*res = new ListNode(carry);
return retHead;
}
};
Add two numbers
最新推荐文章于 2021-02-19 08:37:33 发布