您的位置:首页 > 其它

leetcode:Add Two Numbers

2015-07-15 21:37 447 查看

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
/**
* 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) {
int flag = 0, num1, num2;
ListNode * tmp = NULL;
ListNode * t = (ListNode *)malloc(sizeof(ListNode));
t->next = NULL;
ListNode * p = t;
while(l1 || l2)
{
num1 = l1 ? l1->val : 0;
num2 = l2 ? l2->val : 0;
if(num1 + num2 + flag >= 10)
{
t->val = num1 + num2 + flag - 10;
flag = 1;
}
else
{
t->val = num1 + num2 + flag;
flag = 0;
}
l1 = l1 ? l1->next : NULL;
l2 = l2 ? l2->next : NULL;
tmp = t;
t->next = (ListNode *)malloc(sizeof(ListNode));
t->next->next = NULL;
t = t->next;
}
if(flag)
t->val = 1;
else
tmp->next = NULL;
return p;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: