struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode *head = NULL,*tail = NULL;
int carry = 0;
while (l1 || l2){ //这里的l1和l2在开始的时候是值链表的首地址但是在后面就变成next中的内容,
// 所以,最后链表next里是NULL,就可以通过这个判断是否遍历完整个链表。
int n1 = l1 ? l1->val : 0;
int n2 = l2 ? l2->val : 0;
int sum = n1 + n2 + carry;
if(!head){
//这里给了head和tail,他们在开始时候都是相同的地址,而head作为链表的头指针是不能动的,所以
//tail就是可以移动的临时指针,用来遍历链表用的。
head = tail = malloc(sizeof(struct ListNode));
tail->val = sum % 10;
tail->next = NULL;
}
else{
tail->next = malloc(sizeof(struct ListNode));
tail->next->val = sum % 10;
tail = tail->next;//这里更新了tail的值就是将新的节点的指针传递给临时指针tail
tail->next = NULL;
}
carry = sum /10;
if(l1){
l1 = l1->next;//跳转到下一个节点
}
if(l2){
l2 = l2->next;
}
}
if(carry > 0){
tail->next = malloc(sizeof(struct ListNode));//给进位安排一个新的节点来存储进位
tail->next->val = carry;
tail->next->next = NULL;
}
return head;
}