题解 | #链表相加(二)#
链表相加(二)
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* reverseList(ListNode* head){
ListNode* pre = NULL;
ListNode* temp = head;
while(temp != NULL){
ListNode* cur = temp->next;
temp->next = pre;
pre = temp;
temp = cur;
}
return pre;
}
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
ListNode* new1 = reverseList(head1);
ListNode* new2 = reverseList(head2);
ListNode* cur1 = new1;
ListNode* cur2 = new2;
ListNode* newhead = new ListNode(-1);
ListNode* cur = newhead;
int carry = 0, newval;
while(cur1 != NULL && cur2 != NULL)
{
if(cur1==new1&&cur2==new2){
if((cur1->val + cur2->val)>=10){
carry = 1;
}
newval = (cur1->val + cur2->val) % 10;
}else{
newval = (cur1->val + cur2->val + carry) % 10;
if((cur1->val + cur2->val + carry) >= 10){
carry = 1;
}
else
carry = 0;
}
ListNode* newL = new ListNode(newval);
cur->next = newL;
cur = newL;
cur1 = cur1->next;
cur2 = cur2->next;
}
while(cur1 != NULL){
newval = (cur1->val + carry) % 10;
if((cur1->val + carry) >= 10){
carry = 1;
}
else
carry = 0;
ListNode* newL = new ListNode(newval);
cur->next = newL;
cur = newL;
cur1 = cur1->next;
}
while(cur2 != NULL){
newval = (cur2->val + carry) % 10;
if((cur2->val + carry) >= 10){
carry = 1;
}
else
carry = 0;
ListNode* newL = new ListNode(newval);
cur->next = newL;
cur = newL;
cur2 = cur2->next;
}
if(carry == 1){
ListNode* newL = new ListNode(carry);
cur->next = newL;
}
newhead = newhead->next;
return reverseList(newhead);
}
};