It reports "runtime error", even it can run well on VS2010


  • 0
    L

    I do not want to "new" a new node for every single digit of the sum, I think it may save time to avoid to use too much new operator. So I reuse the nodes of l1 or l2 for the sum.

    There is no error when it run in VS2010, but the web tell "runtime error" when
    l1 = {9,8}, l2 = {1}.

    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode* result;
            ListNode* head = new ListNode(0);
            ListNode* pre;
            int flag = 0;
            int sum;
            
            pre = head;
            
            while(l1 || l2)
            {
                if(!l2)
                {
                    result = l1;
                    sum = l1->val + flag;
                    l1 = l1->next;
                }
                else if(!l1)
                {
                    result = l2;
                    sum = l2->val + flag;
                    l2 = l2->next;
                }
                else
                {
                    result = l1;
                    sum = l1->val + l2->val + flag;
                    l1 = l1->next;
                    l2 = l2->next;
                }
                result->val = sum % 10;
                flag = sum / 10;
                pre->next = result;
                pre = pre->next;
            }
            if(flag)
            {
                pre->next = new ListNode(1);
            }
            
            return head->next;
        }
    };

  • 0
    B

    I got this very same error too. Anybody can help?


  • 0

    Thanks for your feedback. I've fixed this issue. Now your code should get Accepted.


  • 0
    B

    Yes it's fixed. Accepted too.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.