You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
这道题如果采用链表来做的话要考验一下细心程度,最后要判断一下是否有carryout,而不能仅以l1和l2是否为空来判断是否可以返回答案了。
还有C++中链表的节点支持构造器,比如:
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
就可以直接new ListNode(0)来构造一个val=0,next=NULL的新节点了
链表解法:
class Solution
{
int unit,tempsum;
bool carryout=false;
public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
ListNode *pans=new ListNode(0);
ListNode *ans = pans;
if (l1->val + l2->val >= 10)
{
carryout = true;
pans->val = (l1->val + l2->val) % 10;
}
else
{
pans->val = l1->val + l2->val;
carryout = false;
}
l1 = l1->next;
l2 = l2->next;
while (l1 != NULL||l2 != NULL)
{
pans->next = new ListNode(0);
pans = pans->next;
if (l1 != NULL&&l2 != NULL)
{
if (carryout == true)
{
pans->val = 1;
}
tempsum = pans->val + l1->val + l2->val;
if (tempsum >= 10)
{
pans->val = tempsum % 10;
carryout = true;
}
else
{
pans->val = tempsum;
carryout = false;
}
l1 = l1->next;
l2 = l2->next;
}
else if (l1 == NULL&&l2 != NULL)
{
if (carryout == true)
{
pans->val = 1;
}
tempsum = pans->val + l2->val;
if (tempsum >= 10)
{
pans->val = tempsum % 10;
carryout = true;
}
else
{
pans->val = tempsum;
carryout = false;
}
l2 = l2->next;
}
else if (l1 != NULL&&l2 == NULL)
{
if (carryout == true)
{
pans->val = 1;
}
tempsum = pans->val + l1->val;
if (tempsum >= 10)
{
pans->val = tempsum % 10;
carryout = true;
}
else
{
pans->val = tempsum;
carryout = false;
}
l1 = l1->next;
}
}
if (carryout == true)
{
pans->next = new ListNode(1);
}
return ans;
}
};
还有突然发现国外的OJ都是给定了接口,只让你实现一个函数,而不是全部代码都由你编写,做了那么多国内的OJ还是有点不习惯。用面向对象的语言写算法也确实没有面向过程那么习惯。