LeetCode-2. Add Two Numbers

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

题目意思是给出两个用链表表示的倒序的数字,求相加的结果,依旧用链表倒序表示。

思路是个位在前,大的数位在最后,所以从链表头部开始依次相加,进位加1。但是我开始使用了申请空间函数

ans = ans->next = (ListNode *)malloc(sizeof(ListNode));
结果一直超时,malloc函数耗费时间过长,所以参考 http://blog.csdn.net/cmershen/article/details/51548614?locationNum=12&fps=1中的方法,让结果先随便等于l1和l2中不为空的一个,每次申请空间的部分都换成等于l1或l2中不为空的那个,所以可以保证答案的长度与l1和l2中最长的那个保持相等。如果最后有进位则再添加一位。

结论:1.用减法替换取模会快一些;

    2.用别的方法替代malloc函数申请空间;

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* temp = l1 ? l1 : l2;
        ListNode* ans = temp;
        int flag = 0;
        int s = 0;
        while(l1 || l2){
            //ans = ans->next = (ListNode *)malloc(sizeof(ListNode));
            s = flag;
            if(l1){
                s += l1->val;l1 = l1->next;
            }
            if(l2){
                s += l2->val;l2 = l2->next;
            }
            flag = s>9 ? 1 : 0;
            ans->val = flag ? s-10 : s;
            //保证ans与l1、l2中最长的保持一致长度,因为l1和l2也在向后移位
            if (l1) {
                ans = ans->next = l1;
            } else if (l2) {
                ans = ans->next = l2;
            } else {
                ans->next = NULL;
            }
        }
        if(flag){
            ans->next = (ListNode *)malloc(sizeof(ListNode));
            ans = ans->next;
            ans->val = flag;
        }
        ans->next = NULL;
       // temp = temp->next;
        return temp;
    }



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值