/** * 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* addInList(ListNode* head1, ListNode* head2) { // write code here auto l1 = reverse(head1); auto l2 = reverse(head2); auto head = new ListNode(-1); auto cur = head; int t = 0, sum = 0; while(l1 || l2){ sum = t; if(l1){ sum += l1->val; l1 = l1->next; } if(l2){ sum += l2->val; l2 = l2->next; } t = sum / 10; cur->next = new ListNode(sum % 10); cur = cur->next; } if(t) cur->next = new ListNode(t); return reverse(head->next); } ListNode* reverse(ListNode* head){ ListNode* pre = NULL; ListNode* cur = head; ListNode* nex = NULL; while(cur){ nex = cur->next; cur->next = pre; pre = cur; cur = nex; } return pre; } };