为什么我的删除节点函数实际上没有删除节点?

Why isn't my delete node function actually deleting the node?

本文关键字:节点 删除 函数 我的 为什么 实际上      更新时间:2023-10-16

我试图创建一个更像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;
}
}

当要删除的元素是列表的第一个元素时,应将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
}

您需要将head分配给列表中的第二个元素