2. Add Two Numbers

/** * 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) { ListNode * p1 = l1; ListNode * p2 = l2; ListNode * dummy = new ListNode(0); ListNode * p3 = dummy; int sum = 0; int carry = 0; while(l1 != nullptr || l2 != nullptr){ if (l1 != nullptr){ sum += l1->val; l1 = l1->next; } if (l2 != nullptr){ sum += l2->val; l2 = l2->next; } sum += carry; if (sum >= 10){ sum -= 10; carry = 1; } else carry = 0; p3->next = new ListNode(sum); sum = 0; p3 = p3->next; } if (carry == 1) p3->next = new ListNode(1); return dummy->next; } };
Mistakes:
- Sum the boundary is >= 10, or > 9. Do not write > 10...
- Using two lists are better than using one list and iterate on it...
- Remember to reset sum every time you move to a new position.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.