/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *head = (ListNode *)malloc(sizeof(ListNode));
ListNode *p = head;
int cf = 0;
while(l1 || l2){
// 为空指针时,认为取到为0
int num1 = l1 ? l1->val : 0;
int num2 = l2 ? l2->val : 0;
int directNum = num1 + num2 + cf;
// error1:cf 在mod10后才加上
int curVal = (directNum) % 10 ;
// printf("curVal:%d,cf:%d\n" , curVal, cf);
cf = directNum >= 10 ? 1 : 0;
ListNode *curNode = new ListNode(curVal);
p->next = curNode;
p = p->next;
// error2: l1 l2 是空指针时,不可继续用next了
if(l1) l1 = l1->next;
if(l2) l2 = l2->next;
}
// 最后两个数字相加后产生进位
if(cf == 1){
ListNode *curNode = new ListNode(cf);
p->next = curNode;
p = p->next;
}
p->next = NULL;
return head->next;
}
};