List summation (LintCode)

Topic Source: LintCode

Address original title: http://www.lintcode.com/zh-cn/problem/add-two-numbers/

This very simple question, but the point to note pointer operation, remember to initialize, when I submitted forget initialized, although the same output, but still no AC, suggesting Segmentation fault (core dumped), initialization of the AC.
Note that the main point of this question: After the last addition and subtraction, to give out the cycle is determined whether a carry, and if there is the need to create a storage node carry.

Implementation code :

    ListNode *addLists(ListNode *l1, ListNode *l2) 
    {
        if(!l1)
            return l2;
        if(!l2)
            return l1;
        ListNode *l3 = new ListNode(0); //初始化,不然 Segmentation fault (core dumped)
        ListNode *head = l3;

        int jinwei = 0;

        while (l1 || l2)
        {
            int sum = 0;
            if (l1)
            {
                sum += l1->val;
                l1 = l1->next;
            }
            if (l2)
            {
                sum += l2->val;
                l2 = l2->next;
            }
            sum += jinwei;
            ListNode *tmpNode = new ListNode(sum % 10);
            head->next = tmpNode;
            head = head->next;
            jinwei = sum / 10;
        }
        if (jinwei > 0)  //最后有进位,需要新建一个节点
        {
            ListNode *tmpNode = new ListNode(jinwei);
            head->next = tmpNode;
            head = head->next;
        }
        return l3->next;
    }

Guess you like

Origin blog.csdn.net/Asunqingwen/article/details/78301440