题解 | #链表相加(二)#
链表相加(二)
http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/**
* 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* addInList(ListNode* head1, ListNode* head2) {
// write code here
if(!head1) return head2; //翻转链表,从个位开始加
if(!head2) return head1;
head1 = reverse(head1);
head2 = reverse(head2);
ListNode* ans = new ListNode(-1);
ListNode* cur = ans;
int tmp = 0; //tmp为进位值
while(head1 || head2){ //当节点不为空时
int val = tmp; //val为当前位之和,val = 进位值 + head1当前位值 + head2当前位值
if(head1){
val += head1->val;
head1 = head1->next;
}
if(head2){
val += head2->val;
head2 = head2->next;
}
tmp = val / 10;
ListNode* tmpNode = new ListNode(val%10);
cur->next = tmpNode;
cur = cur->next;
}
return reverse(ans->next);
}
ListNode* reverse(ListNode* head){
if(!head) return nullptr;
ListNode* pre = nullptr;
ListNode* nex = nullptr;
ListNode* cur = head;
while(cur){
nex = cur->next;
cur->next = pre;
pre = cur;
cur = nex;
}
return pre;
}
};