C
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
int num1 = 0; int num2 = 0;
int t = 0;
struct ListNode* t1 = l1;
struct ListNode* t2 = l2;
struct ListNode *res = (struct ListNode*)malloc(sizeof(struct ListNode));
res->next = NULL;
struct ListNode *s = res;
for(int i=0 ; t1 != NULL || t2 != NULL || t != 0; i++)
{
num1 = 0;
num2 = 0;
s->val = 0;
if( t1 != NULL){
s->val += t1->val;
t1 = t1->next;
}
if( t2 != NULL){
s->val += t2->val;
t2 = t2->next;
}
s->val +=t;
t = s->val/10;
s->val = s->val % 10;
if(t1 != NULL || t2 != NULL || t != 0){
s->next = (struct ListNode*)malloc(sizeof(struct ListNode));
s = s->next;
s->next = NULL;
}
}
return res;
}
C++
/**
* 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* res = new ListNode(0);
ListNode* p = res;
ListNode* p1 = l1;
ListNode* p2 = l2;
int flag = 0;
while(p1 || p2 ||flag){
int tmp = 0;
if (p1 != nullptr) tmp += p1->val;
if (p2 != nullptr) tmp += p2->val;
tmp += flag;
flag = tmp / 10;
tmp %= 10;
ListNode* add = new ListNode(tmp);
p->next = add;
p = p->next;
p1 = (p1 ? p1->next : nullptr);
p2 = (p2 ? p2->next : nullptr);
}
return res->next;
}
};
感谢点赞!!!