题解 | #链表相加(二)#
链表相加(二)
http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
ListNode* head1Reversed = reverse(head1);
ListNode* head2Reversed = reverse(head2);
int jinwei = 0;
ListNode* res = nullptr;
while(jinwei || head1Reversed || head2Reversed) {
int nodeVal1 = head1Reversed?head1Reversed->val:0;
int nodeVal2 = head2Reversed?head2Reversed->val:0;
jinwei += (nodeVal1 + nodeVal2);
ListNode* node = new ListNode(jinwei%10);
node->next = res;
res=node;
jinwei = jinwei/10;
if(head1Reversed) {
head1Reversed = head1Reversed->next;
}
if(head2Reversed) {
head2Reversed = head2Reversed->next;
}
}
return res;
}
ListNode* reverse(ListNode* head) {
ListNode* res = new ListNode(-1);
while(head) {
ListNode* temp = head->next;
head->next=res->next;
res->next=head;
head = temp;
}
return res->next;
}
};