一个循环内从左向右加,当l1==NULL && l2==NULL 退出,如果有进位额外申请一个节点保存进位:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *dummyhead = malloc(sizeof(struct ListNode));
dummyhead->next = NULL;
int val, carry = 0;
struct ListNode *node ,*last;
last = dummyhead;
while(1){
if(l1&&l2){
val = (l1->val+l2->val+carry)%10;
carry = (l1->val+l2->val+carry)/10;
l1 = l1->next;
l2 = l2->next;
}else if(l1 != NULL && l2 == NULL){
val = (l1->val + carry)%10;
carry = (l1->val+carry)/10;
l1 = l1->next;
}else if(l1 == NULL && l2 != NULL){
val = (l2->val + carry)%10;
carry = (l2->val+carry)/10;
l2 = l2->next;
}else
break;
node = malloc(sizeof(struct ListNode));
node->val = val;
node->next = NULL;
last->next = node;
last = last->next;
}
if(carry){
node = malloc(sizeof(struct ListNode));
node->val = carry;
node->next = NULL;
last->next = node;
}
return dummyhead->next;
}