题解 | #链表相加(二)#高精度加法模板
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
最好理解的高精度加法模板:(不到30行)
class Solution { public: ListNode* reverse(ListNode* head){ ListNode* p = NULL, *q = head; while(q){ auto r = q->next; q->next = p; p = q, q = r; } return p; } ListNode* addInList(ListNode* head1, ListNode* head2) { head1 = reverse(head1), head2 = reverse(head2); int t = 0; // 进位标致 auto p = head1, q = head2; ListNode* dummy = new ListNode(-1); auto o = dummy; while(p || q || t){ if(p) t += p->val, p = p->next; if(q) t += q->val, q = q->next; o->next = new ListNode(t % 10); t /= 10; o = o->next; } return reverse(dummy->next); } };