【发布时间】:2017-12-12 00:33:46
【问题描述】:
我有这个结构:
struct Node {
int num;
Node *next;
Node(int, Node*);
};
类内Collection。
当我尝试删除列表的最后一个元素时,使用此函数:
void Collection::remove(int num){
Node *target = find(num);
if (target == nullptr) return;
n--;
Node *temp = target ->next;
if (temp == nullptr) {
delete target;
target = nullptr; // This is where the problem occurs
return;
}
target->num = temp->num;
target->next = temp->next;
delete temp;
}
之前Node的*next仍然指向现在为空的地址位置,如何将target内存位置设置为null?
更多信息,这是我的功能find()
Collection::Node* Collection::find(int num) {
Node *temp = head;
while (temp != nullptr && temp->num != num) temp = temp->next;
return temp;
}
【问题讨论】:
标签: c++ pointers struct singly-linked-list nullptr