第一反应是,怎么直接怎么来:取出两个链表中的数执行加法得到结果值,然后构造一个新的链表将结果只逆序插入之后进行返回,但是细想这个思路除了直接就没有优点了,而且测试之后容易发生溢出错误。
考虑进位传递的思路:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
auto head = new ListNode, cur = head;
int x = 0; //进位
while(l1 && l2){
cur->next = new ListNode((l1->val + l2->val + x) % 10);
cur = cur->next;
x = (l1->val + l2->val + x) / 10;
l1 = l1->next;
l2 = l2->next;
}
auto l = l1 == NULL ? l2 : l1;
while(l){
cur->next = new ListNode((l->val + x)%10);
cur = cur->next;
x = (l->val + x) / 10;
l = l->next;
}
if(x) cur->next = new ListNode(x);
return head->next;
}
};
一次循环解决,其实思路和上面是差不多的。
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
auto head = new ListNode, cur = head;
int x = 0; //进位
while(true){
int sum = 0;
if(l1 != NULL) sum += l1->val;
if(l2 != NULL) sum += l2->val;
sum += x;
x = sum / 10;
cur->next = new ListNode(sum % 10);
cur = cur->next;
if(l1 != NULL) l1 = l1->next;
if(l2 != NULL) l2 = l2->next;
if(l1 == NULL && l2 == NULL && x == 0) break;
}
return head->next;
}
};