class Solution {
public:
ListNode* addInList(ListNode* head1, ListNode* head2) {
ListNode* l1 = reverseList(head1);//翻转链表1
ListNode* l2 = reverseList(head2);//翻转链表2
ListNode* head = nullptr;
ListNode* tail = nullptr;
int carry = 0; //进位
while (l1 || l2) {
int n1 = l1 ? l1->val : 0;
int n2 = l2 ? l2->val : 0;
int sum = n1 + n2 + carry;
if (!head) {
head = new ListNode(sum % 10);
tail = head;
} else {
tail->next = new ListNode(sum % 10);
tail = tail->next;
}
if (l1) l1 = l1->next;//循环
if (l2) l2 = l2->next;
carry = sum / 10;
}
tail->next = carry ? new ListNode(carry) : nullptr;//尾部节点
ListNode* pHead = reverseList(head);
return pHead;
}
ListNode* reverseList(ListNode* head) {//翻转链表
ListNode* cur = head;
ListNode* pre = nullptr;
while (cur) {
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};