题目:
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
Subscribe to see which companies asked this question
代码:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *p1 = l1, *p2 = l2, *ahead = NULL, *p = NULL;
int carry = 0;
while(p1 || p2 || carry)
{
int tp = 0;
if(p1)
{
tp += p1->val;
}
if(p2)
{
tp += p2->val;
}
if(carry)
tp += carry;
if(p1)
p1 = p1->next;
if(p2)
p2 = p2->next;
if(tp >= 10)
{
carry = 1;
tp %= 10;
}
else
carry = 0;
if(!ahead)
{
ahead = new ListNode(tp);
p = ahead;
}
else
{
p->next = new ListNode(tp);
p = p->next;
}
}
return ahead;
}
};