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

程序:

class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
        int len1 = link_size(l1);
        int len2 = link_size(l2);

        if (len1 == 0 || len2 == 0)
            return len1 == 0 ? l2 : l1;
        if (len2 > len1)
        {
            ListNode *t = l1;
            l1 = l2;
            l2 = t;
        }
        //cout << len1 << endl;

        //ListNode *ret = (ListNode*)malloc(sizeof(ListNode));
        ListNode *ret = new ListNode(-1);
        ListNode *temp, *r;
        r = ret;
        //ListNode *ret = l1;
        int a = 0, b = 0, c = 0, flag = 0;
        //ListNode *temp = (ListNode*)malloc(sizeof(ListNode));
        while (l1)
        {
            a = l1->val;
            if (l2)
                b = l2->val;
            else
                b = 0;
            if (flag)
                c = a + b + 1;
            else
                c = a + b;
            if (c > 9)
                flag = 1;
            else
                flag = 0;

            c = c % 10;
            temp = new ListNode(c);
            //temp->val = c;
            r->next = temp;
            r = temp;
            /*l1->val = c;*/

            l1 = l1->next;
            if (l2)
                l2 = l2->next;//若l1比l2长,则l2到头后不能再继续否则会造成栈溢出
            /*if (l1->next == NULL)
            temp = l1;*/
        }

        if (flag)
        {
            ListNode *p = new ListNode(1);
            //p->val = 1;
            p->next = NULL;
            r->next = p;
            r = p;
        }

        //cout << link_size(l1) << endl;
        r->next = NULL;
        return ret->next;
        //return ret;
    }

    int link_size(ListNode *l)
    {
        int size = 0;
        while (l)
        {
            size++;
            l = l->next;
        }
        return size;
    }
};

点评:

段错误:您的程序发生段错误,提示程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)
原因是l2到头后还在继续向前,在vs上调试的测试案例是等长,以后需要用更多的测试案例来调试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值