-1
我給出了兩個表示兩個非負數的鏈表。數字以相反的順序存儲,每個節點都包含一個數字。我必須編寫一個代碼,將兩個數字相加並將其作爲鏈接列表返回(也按相反的順序)。爲什麼我的代碼導致運行時錯誤?
我寫了下面的代碼。只要最後一位數字不是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;
}
};
用來解決這個問題的正確工具是您的調試器。在最後,你可以找出哪條線路導致錯誤 – UnholySheep
取得本地變量的地址是災難(&last)的配方。在聲明的範圍之外,它將是無效的 – crashmstr
你是否真的認爲在子例程退出到鏈表尾部時添加一個指向局部變量的指針是個好主意? – infixed