题目:
ac代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
int carry = 0;
struct ListNode* L1 = l1;
struct ListNode* L2 = l2;
struct ListNode* L3;
struct ListNode* l3 = (struct ListNode*)malloc(sizeof(struct ListNode));
l3->val = (l1->val+l2->val)%10;
if((l1->val+l2->val)>=10)
carry = 1;
l1 = l1->next;
l2 = l2->next;
l3->next = NULL;
L3 = l3;
while(l1!=NULL &&l2 != NULL){
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = (l1->val+l2->val+carry)%10;
node->next = NULL;
l3->next = node;
l3 = l3->next;
if((l1->val+l2->val+carry)>=10)
carry = 1;
else
carry = 0;
l1 = l1->next;
l2 = l2->next;
}
while(l1!=NULL){
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = (l1->val+carry)%10;
node->next = NULL;
l3->next = node;
l3 = l3->next;
if((l1->val+carry)>=10)
carry = 1;
else
carry = 0;
l1 = l1->next;
}
while(l2!=NULL){
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = (l2->val+carry)%10;
node->next = NULL;
l3->next = node;
l3 = l3->next;
if((l2->val+carry)>=10)
carry = 1;
else
carry = 0;
l2 = l2->next;
}
if(carry == 1){
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = 1;
node->next = NULL;
l3->next = node;
}
return L3;
}
时间复杂度:O(m+n)