我正在尝试创建一个更像是C链表的链表,但是它并没有永久删除该节点。运行函数后,当我打印出链接列表时,该节点仍然存在。为什么我的删除节点功能实际上没有删除节点?
bool removeFromList(int delID, node* &head){
node* temp = new node;
node* curr = head;
while(curr != NULL && curr->id != delID){
temp = curr;
curr = curr->next;
}
if(curr == NULL){
cout << delID << " was not in the has table." << endl;
return false;
}
else{
node* next = curr->next;
cout << "Node with id " << curr->id << " was deleted." << endl;
delete curr;
curr = NULL;
temp->next = next;
return true;
}
}
答案 0 :(得分:0)
当要删除的元素是列表的第一个元素时,应将head分配给列表的第二个(如果存在)元素。那就是:
bool removeFromList(int delID, node* &head){
//Checking for the front of the list
if (head != NULL && head->id == delID){
head = head->next;
return true;
}
node* temp; //You don't need to initialize this
...//the rest of your code may remains equal
}
答案 1 :(得分:0)
您需要将head分配给列表中的第二个元素