为什么我的代码导致运行时错误?

时间:2016-12-06 20:27:15

标签: c++ pointers runtime-error

我有两个代表两个非负数的链表。数字以相反的顺序存储,每个节点包含一个数字。我必须编写一个代码,添加两个数字并将其作为链接列表返回(也以相反的顺序)。

我写了以下代码。只要最后一个数字不是9,它就可以正常工作。看起来这是一个内存分配问题,但我无法弄清楚是什么。

任何人都可以提出错误以及如何解决问题吗?

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/

void adder(int &value, bool &carry) {
   if(carry) value++;
   if (value > 9) {
      value = value%10;
      carry = true;
   }else carry = false;
}

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* prev = NULL;
        bool carry = false;
        ListNode* curr1 = l1;
        ListNode* curr2 = l2;
        ListNode* worker = NULL;

        while(curr1 != NULL && curr2 != NULL){
            curr1 = curr1->next;
            curr2 = curr2->next;
        }

        if(curr1 != NULL) worker = l1;
        else worker = l2;

        ListNode* result = worker;
        curr1 = l1;
        curr2 = l2;

        while(curr1 != NULL && curr2 != NULL) {
            int value = curr1->val + curr2->val ;
            adder(value, carry);
            worker->val = value;
            //cout<<curr1->val<<endl;
            curr1 = curr1->next;
            curr2 = curr2->next;
            prev = worker ;
            worker = worker->next;
        }

        while(worker != NULL && carry) {
            int value = worker->val;
            adder(value, carry);
            worker->val = value;
            prev = worker;
            worker = worker->next;
        }

        ListNode last(1);

        //the following line results in runtime error
        if(carry) {
            prev->next = &last;
        }

        return result; 

    }
};

1 个答案:

答案 0 :(得分:0)

您至少有两个明显的错误。 首先,至少我无法保证{/ 1}}

prev

非NULL。这是算法逻辑中的错误。 第二次,您要将本地对象prev->next = &last; 添加到链接列表中。相反,您应该使用last分配新的ListNode,例如

new