当我在C ++中删除节点对象时,有什么我忘记了吗? 我很困惑为什么我的删除方法适用于主要方法,但在测试时我的教授的主要方法不起作用。
这是我的一些删除方法的代码。
// this is his method header
void remove (const E& x) {
// passes in the head pointer, and the object to delete.
_remove(head, x);
}
// Recursive remove function
void _remove(Node* &curr, const E& val){
// if the head is null do nothing.
// base case
if (curr == NULL){
return;
}
//case where the node found is the head.
if (curr->data == val && curr == head){
head = head->next;
delete curr;
return;
}
// the node may be in the middle somewhere
if (curr->next->data == val){
Node* del = curr->next;
curr->next = del->next;
delete del;
return;
}
// rinse and repeat.
_remove(curr->next, val);
}