1题目
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
2解答
最开始没仔细看,以为是按照高位到地位存放的,要反过来再加。没有编译错误,一次性通过还是有点小难度,毕竟平时养成了多次运行+分析的习惯,这个是错误的,算法题最好的思路就是先做用例,然后再写,这样可避免自己漏掉情况,比如最容易的就是最后那个判断。下面这种写法,其实还是有一些问题,最开始的边界判断直接返回了参数传过来的值,也就是做调用者在做返回值资源释放的时候就可能出问题了。
/**
* 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 = 0;
ListNode** ppre = &result;
int sum = 0;
while(l1)
{
if (!l2)
break;
sum += l1->val + l2->val;
l1 = l1->next;
l2 = l2->next;
*ppre = new ListNode(sum % 10);
ppre = &((*ppre)->next);
sum /= 10;
}
while(l1)
{
sum += l1->val;
l1 = l1->next;
*ppre = new ListNode(sum % 10);
ppre = &((*ppre)->next);
sum /= 10;
}
while(l2)
{
sum += l2->val;
l2 = l2->next;
*ppre = new ListNode(sum % 10);
ppre = &((*ppre)->next);
sum /= 10;
}
if (sum)
{
*ppre = new ListNode(sum);
}
return result;
}
};