leetcode_add two nums

题解参考:https://discuss.leetcode.com/topic/53268/efficient-and-clean-iterative-and-recursive-solutions-in-c/2

这是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,发现自己完全忘了迭代和递归这回事,思维非常僵化,也没用上题目给的数据结构体的构造函数,汗……

以下是别人的思路:

  1. 迭代
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;
    }
};
  1. 递归
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++的语法不够熟悉,哎。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值