题解 | #链表相加(二)#
链表相加(二)
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* addInList(ListNode* head1, ListNode* head2) { head1=ReverseList(head1); head2=ReverseList(head2); ListNode* res=new ListNode(-1); ListNode* ptr=res; int num=0; while(head1||head2||num) { if(head1) { num+=head1->val; head1=head1->next; } if(head2) { num+=head2->val; head2=head2->next; } ptr->next=new ListNode(num%10); num/=10; ptr=ptr->next; } return ReverseList(res->next); } ListNode* ReverseList(ListNode* head) { if(head==nullptr||head->next==nullptr) return head; ListNode* last=ReverseList(head->next); head->next->next=head; head->next=nullptr; return last; } };