题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */ ListNode* reverseList(ListNode* head) { ListNode* cur = head; ListNode* pre = nullptr; while(cur) { ListNode* next = cur->next; cur->next = pre; pre=cur; cur=next; } return pre; } ListNode* addInList(ListNode* head1, ListNode* head2) { // write code here ListNode* cur1 = reverseList(head1);//翻转链表 ListNode* cur2 = reverseList(head2);//翻转链表 ListNode* resHead=nullptr; int cnt = 0; int x1=0,x2=0,sum=0; while(cur1 || cur2) { //如果两个值的加和>10,就会产生进位,这个用来存储进位 if(cur1==nullptr) x1=0; else x1=cur1->val; if(cur2==nullptr) x2=0; else x2=cur2->val; sum = x1+x2+cnt; cnt = sum / 10; ListNode* tmpNode = new ListNode(sum%10); tmpNode->next = resHead; resHead = tmpNode; if(cur1) cur1=cur1->next; if(cur2) cur2=cur2->next; } // 如果cnt>0 那么就说明存在进位还得插入一个节点 if(cnt > 0) { ListNode* newNode = new ListNode(cnt); newNode->next = resHead; resHead = newNode; } return resHead; } };