您的位置:首页 > 其它

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: