/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
ListNode* RverseList(ListNode* pHead) {
ListNode* nex = nullptr;
ListNode* pre = nullptr;
ListNode* cur = pHead;
// ListNode* next = nullptr;
if(!pHead) {
return nullptr;
}
while(cur) {
nex = cur->next;
cur->next = pre;
pre = cur;
cur = nex;
}
return pre;
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
if(!head1) {return head2;}
if(!head2) {return head1;}
ListNode* p1 = RverseList(head1);
ListNode* p2 = RverseList(head2);
int carry = 0;
auto res = new ListNode(-1);
ListNode* curr = res; // 必须用头结点拷贝才能操作next
while(p1 || p2 || carry){ // 有一个不为零的就需要继续加运算
int a = p1 ? p1->val : 0; // 有节点的就读取结点上的数据,没节点就设置为0
int b = p2 ? p2->val : 0;
int temp = b + a + carry; // 计算两个值和进位的和
carry = temp / 10; // 计算下一次进位
temp = temp % 10; // 计算当前位的数字
curr->next = new ListNode(temp); // 创建新节点保存数
curr = curr->next;
if(p1) { // 将结点向后推进
p1 = p1->next;
}
if(p2) {
p2 = p2->next;
}
}
return RverseList(res->next);
}
};