445. Add Two Numbers II
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode * addTwoNumbers(ListNode *l1, ListNode *l2) { if(l1 == NULL) return l2; if(l2 == NULL) return l1; int flag = 0; ListNode* res = new ListNode(0); ListNode* tmp = new ListNode(0); res = tmp; l1 = reverse(l1); l2 = reverse(l2); while(l1 != NULL || l2 != NULL){ int a = l1 == NULL?0:l1->val; int b = l2 == NULL?0:l2->val; ListNode *ss = new ListNode((a+b+flag)%10); flag = (a+b+flag) /10; tmp->next = ss; tmp = ss; l1 = l1 == NULL? NULL:l1->next; l2 = l2 == NULL? NULL:l2->next; } if(flag == 1){ ListNode* ss = new ListNode(1); tmp->next = ss; } return reverse(res->next); } ListNode *reverse(ListNode *pHead) { ListNode * dummy = new ListNode(-1); ListNode * pCur = pHead; ListNode * pNext = nullptr; while (pCur) { pNext = pCur->next; pCur->next = dummy->next; dummy->next = pCur; pCur = pNext; } return dummy->next; } };