这是leetcode第二题,属于medium难度,题目如下:
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
我在没看discuss之前思路如下:
将问题分为三类
l1长度大于l2;
l1长度小于l2;
l1长度与l2长度相等。
然后再一次写各个类别的代码,在写完后真的很长很长,并且我的逻辑思维完全混乱了,重写了几次才写好得到了AC。直到我打开了discuss,发现自己完全忘了迭代和递归这回事,思维非常僵化,也没用上题目给的数据结构体的构造函数,汗……
以下是别人的思路:
- 迭代
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
int c = 0;
ListNode newHead(0);
ListNode *t = &newHead;
while(c || l1 || l2)
{
c += (l1? l1->val : 0) + (l2? l2->val : 0);
t->next = new ListNode(c%10);
t = t->next;
c /= 10;
if(l1) l1 = l1->next;
if(l2) l2 = l2->next;
}
return newHead.next;
}
};
- 递归
class Solution
{
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
if(!l1 && !l2) return NULL;
int c = (l1? l1->val:0) + (l2? l2->val:0);
ListNode *newHead = new ListNode(c%10), *next = l1? l1->next:NULL;
c /= 10;
if(next) next->val += c;
else if(c) next = new ListNode(c);
newHead->next = addTwoNumbers(l2? l2->next:NULL, next);
return newHead;
}
};
总结:
对于指针和结构体基本上没印象了,得去补补。此外,把问题想复杂了,应该直接把相对短的list补0,然后就不需要自己再去纠结哪个长哪个
短导致自己思维混乱了,更让自己愧疚的是对c++的语法不够熟悉,哎。