思路:先对两个链表进行反转,反转求和注意进位运算,求和完成之后再进行反转得到结果
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <cstddef>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
ListNode* phead1 = ReverseList(head1);
ListNode* phead2 = ReverseList(head2);
int i= 0;
ListNode* result = new ListNode(0);
ListNode* ret = result;
while(phead2||phead1||i>0){
int val1 = phead1?phead1->val:0;
int val2 = phead2?phead2->val:0;
int sum = val1 + val2 + i;
i = sum/10;
sum = sum%10;
ret->next = new ListNode(sum);
ret = ret->next;
if(phead1) phead1 = phead1->next;
if(phead2) phead2 = phead2->next;
}
return ReverseList(result->next);
}
ListNode* ReverseList(ListNode* head){
ListNode* ret = nullptr;
ListNode* temp = nullptr;
while(head){
temp = head->next;
head->next = ret;
ret = head;
head = temp;
}
return ret;
}
};