题解 | #链表相加(二)#
链表相加(二)
https://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* s) { ListNode* nex = NULL; ListNode* pre = NULL; ListNode* cur = s; while(cur!=NULL) { nex = cur->next; cur->next = pre; pre = cur; cur = nex; } return pre; } ListNode* addInList(ListNode* head1, ListNode* head2) { // write code here head1 = reverseList(head1); head2 = reverseList(head2); ListNode*tmp1 = head1; ListNode*tmp2 = head2; int n = 1; int m= 1; while(tmp1->next!=NULL) { tmp1 = tmp1->next; n++; } while(tmp2->next!=NULL) { tmp2 = tmp2->next; m++; } if(n>m) { for(int i = 0;i<(n-m);i++) { tmp2->next = new ListNode(0); tmp2 =tmp2->next; } } else if(n<m) { for(int i = 0;i<(m-n);i++) { tmp1->next = new ListNode(0); tmp1 = tmp1->next; } } int count = 0; int val = 0; ListNode* phead3 = new ListNode(-1); ListNode*w = phead3; ListNode*res = w; int nums = 0; while(head1!=NULL) { nums++; val = count+head1->val+head2->val; w->next = new ListNode(val%10); count = val/10; if(nums==1) { res = w->next; } w = w->next; head1 = head1->next; head2 = head2->next; } if(count>=1) { w->next = new ListNode(count); w=w->next; } head1 = reverseList(res); return head1; } };