LeetCode – Refresh – Add Two Numbers
2015-03-18 07:04
369 查看
Same with add binary. You can also skip delete the result pointer. But just return result->next. Depends on the interviewer.
/** * 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) return l2; if (!l2) return l1; ListNode *result = new ListNode(0); ListNode *runner = result; int carry = 0, sum = 0; while (l1 || l2) { sum = carry; if (l1) { sum += l1->val; l1 = l1->next; } if (l2) { sum += l2->val; l2 = l2->next; } carry = sum/10; runner->next = new ListNode(sum%10); runner = runner->next; } if (carry) { runner->next = new ListNode(carry); } runner = result->next; delete result; return runner; } };
相关文章推荐
- 【Leetcode】【python】Add Two Numbers
- LeetCode 2. Add Two Numbers 解题报告
- leetcode-2-Add Two Numbers
- [leetcode刷题系列]Add Two Numbers
- LeetCode: Add Two Numbers
- LeetCode # Add Two Numbers #
- leetcode Add Two Numbers(Java)
- LeetCode刷题(2)——AddTwoNumbers
- LeetCode之 AddTwoNumbers
- Leetcode - Add Two Numbers
- [leetcode] Add Two Numbers
- LeetCode Add Two Numbers
- LeetCode -- Add Two Numbers
- LeetCode [Day 4] Add Two Numbers 题解
- leetcode--Add Two Numbers
- LeetCode-[Add Two Numbers]
- LeetCode题解:Add Two Numbers
- LeetCode(2)Add Two Numbers
- Leetcode 解题 Add Two Numbers Python
- leetcode2 add two numbers