最少空间:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/* 额外空间使用最小 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
int sum = 0;
int flag = 0;
struct ListNode * head;
head = l1;
sum = l1->val + l2->val + flag;
l1->val = sum % 10;
flag = sum / 10;
while(l1->next != NULL && l2->next != NULL){
l1 = l1->next;
l2 = l2->next;
sum = l1->val + l2->val + flag;
l1->val = sum % 10;
flag = sum / 10;
}
if(l1->next == NULL)
l1->next = l2->next;
while(l1->next != NULL && flag){
l1 = l1->next;
sum = l1->val + flag;
l1->val = sum % 10;
flag = sum / 10;
}
if (flag) {
l1->next = (struct ListNode *)malloc(sizeof(struct ListNode));
l1->next->next = NULL;
l1->next->val = flag;
}
return head;
}
更简洁些的实现:
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
if (NULL == l1) return l2;
if (NULL == l2) return l1;
// 链表都不为空
struct ListNode tmp;
struct ListNode *next = &tmp;
struct ListNode *node = NULL;
int val;
int flag = 0; //进位
while (l1 || l2 || flag) {
val = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + flag;
flag = val / 10;
val = val % 10;
if (l1) {
l1->val = val;
next->next = l1;
} else if (l2) {
l2->val = val;
next->next = l2;
} else {
node = (struct ListNode *)malloc(sizeof (struct ListNode));
node->val = val;
node->next = NULL;
next->next = node;
}
next = next->next;
l1 = l1 ? l1->next : NULL;
l2 = l2 ? l2->next : NULL;
}
return tmp.next;
}