您的位置:首页 > 其它

[LeetCode] Add Two Numbers

2014-03-11 20:07 267 查看
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Solutions:

/**
* 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 *ans = NULL, *end = NULL, *num1 = l1, *num2 = l2;
int carry = 0, sum = 0;
while(true)
{
if(num1 != NULL)
{
if(num2 != NULL)
{
sum = num1 -> val + num2 -> val + carry;
carry = sum / 10;
if(ans == NULL)
{
ans = new ListNode(sum % 10);
end = ans;
}
else
{
end -> next = new ListNode(sum % 10);
end = end -> next;
}
num1 = num1 -> next;
num2 = num2 -> next;
}
else
{
sum = num1 -> val + carry;
carry = sum / 10;
if(ans == NULL)
{
ans = new ListNode(sum % 10);
end = ans;
}
else
{
end -> next = new ListNode(sum % 10);
end = end -> next;
}
num1 = num1 -> next;
}
}
else
{
if(num2 != NULL)
{
sum = num2 -> val + carry;
carry = sum / 10;
if(ans == NULL)
{
ans = new ListNode(sum % 10);
end = ans;
}
else
{
end -> next = new ListNode(sum % 10);
end = end -> next;
}
num2 = num2 -> next;
}
else
{
if(carry == 1)
{
end -> next = new ListNode(1);
end = end -> next;
}
break;
}
}
}

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