1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode *first_l1 = l1, *first_l2 = l2; ListNode *ans = new ListNode(0); ListNode *root = ans; int flag = 0; int aux = 0; int x, y; while(first_l1 || first_l2) { if(first_l1) x = first_l1->val; else x = 0; if(first_l2) y = first_l2->val; else y = 0; aux = x + y + flag; flag = aux / 10; aux = aux % 10;
ListNode *temp = new ListNode(aux); ans->next = temp; ans = ans->next;
if(first_l1) first_l1 = first_l1->next; if(first_l2) first_l2 = first_l2->next; } if(flag) { ListNode *temp = new ListNode(1); ans->next = temp; } return root->next; } };
class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode ans(0), *p = &ans; int aux = 0, flag = 0; while(l1 || l2 || flag) { aux = 0; if(l1) aux += l1->val; if(l2) aux += l2->val; aux += flag; flag = aux / 10; aux = aux % 10;
ListNode *new_node = l1 ? l1 : l2; if(nullptr == new_node) new_node = new ListNode(aux);
new_node->val = aux; p->next = new_node; p = p->next; if(l1) l1 = l1->next; if(l2) l2 = l2->next; } return ans.next; } };
|