官方的题解,醍醐灌顶啊。首先就是先翻转两个链表,这样就可以按顺序相加,之后对结果链表再翻转一遍就可以了
具体代码如下所示:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* reverseList(ListNode *pHead){
if(pHead==NULL) return NULL;
ListNode *cur = pHead;
ListNode *pre = NULL;
while(cur){
ListNode *pNext = cur->next;
cur->next = pre;
pre=cur;
cur = pNext;
}
return pre;
}
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
if(head1==NULL) return head2;
if(head2==NULL) return head1;
head1 = reverseList(head1);
head2 = reverseList(head2);
ListNode *res = new ListNode(-1);
ListNode *head = res;
int carry = 0;
while(head1||head2||carry){
int val1 = head1==NULL ? 0 : head1->val;
int val2 = head2==NULL ? 0 : head2->val;
int tmp = val1 + val2 + carry;
carry = tmp/10;
tmp%=10;
head->next=new ListNode(tmp);
head=head->next;
if(head1 != NULL){
head1 = head1->next;
}
if(head2 != NULL){
head2 = head2->next;
}
}
return reverseList(res->next);
}
};