题解 | #链表相加(二)#
链表相加(二)
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 reverse(ListNode* head) { ListNode* pre = nullptr; ListNode* tmp = head ->next ; while(head) { head ->next = pre ; pre = head ; head = tmp ; tmp = head ->next ; } return pre ; } ListNode* addInList(ListNode* head1, ListNode* head2) { // write code here ListNode* h1 = reverse(head1), h2 = reverse(head2) ; / cout<val<<endl<val;/ int pro = 0; ListNode ww = new ListNode(0); ListNode* w = ww ; while(h1 && h2) { ListNode* nw = new ListNode(0); nw->val = (h1->val + h2 ->val + pro )%10; pro = (h1->val + h2 ->val + pro)/10; w ->next = nw ; w = w ->next; h1 = h1 -> next ; h2 = h2 ->next ; } while(h1) { ListNode* nw = new ListNode(0); nw->val = ((h1->val ) + pro)%10 ; pro = (h1->val + pro)/10; w ->next = nw; w = w->next; h1 = h1 ->next ; cout<<"123"<<endl<<ww;
}
while(h2)
{
ListNode* nw = new ListNode(0);
nw->val = ((h2->val ) + pro)%10 ;
pro = (h2->val + pro)/10;
w ->next = nw;
w = w->next;
h2 = h2 ->next ;
}
if(pro == 1)
{
ListNode* nw = new ListNode(1);
w ->next = nw;
w = w->next;
}
ListNode *www = ww->next;
return reverse(www) ;
}
};