- 这是第一次按照最初的思路写出来的
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* l = (struct ListNode*)malloc(sizeof(struct ListNode));
l->next = NULL;
struct ListNode* p = l;
int flag=0;
while(l1&&l2){
int temp = l1->val+l2->val+flag;
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->next = NULL;
p->next = node;
p = node;
node->val = temp%10;
flag = temp/10;
l1 = l1->next;
l2 = l2->next;
}
if(l1){
while(l1){
int temp = l1->val+flag;
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->next = NULL;
p->next = node;
p = node;
node->val = temp%10;
flag = temp/10;
l1 = l1->next;
}
}else if(l2){
while(l2){
int temp = l2->val+flag;
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->next = NULL;
p->next = node;
p = node;
node->val = temp%10;
flag = temp/10;
l2 = l2->next;
}
}
if(flag!=0){
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->next = NULL;
p->next = node;
p = node;
node->val =flag;
}
return l->next;
}
2.这是考虑到l1 l2不需要再保留了,减少分配空间的代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* l = (struct ListNode*)malloc(sizeof(struct ListNode));
l->next = NULL;
struct ListNode* p = l;
int flag=0;
while(l1||l2){
int temp = (l1!=NULL?l1->val:0)+(l2!=NULL?l2->val:0)+flag;
flag = temp/10;
if(l1){
l1->val = temp%10;
p->next = l1;
p = l1;
l1 = l1->next;
if(l2) l2 = l2->next;
}else{
l2->val = temp%10;
p->next = l2;
p = l2;
l2 = l2->next;
}
}
if(flag!=0){
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->next = NULL;
p->next = node;
p = node;
node->val =flag;
}
return l->next;
}
image.png