从链表中删除节点
Removing a node from a linked-list
>我已经创建了一个哈希表,我想从链接列表中删除一个节点。该代码适用于删除第一个节点,但不适用于删除其他节点。
void intHashTable::remove(int num){
int location = ((unsigned)num) % size;
Node * runner = table[location];
int checker;
if(runner->next == NULL){
if(num == table[location]->num){
table[location] = NULL;
}
}else{
if(table[location]->num == num){
table[location] = table[location]->next;
}else{
//This part doesn't seem to be working.
Node *temp = runner->next;
while(temp != NULL){
if(temp->num == num){
runner->next = temp->next;
delete(temp);
break;
}
}
}
}
}
您尚未更新temp
以指向循环中的下一项:
temp = temp->next;
您似乎还表示表中带有NULL
指针的空行,但您在代码中没有正确处理这种情况 - 如果runner
NULL
则当您尝试在第一次检查中访问runner->next
时,您将崩溃。此外,在某些情况下,您无法删除节点。
若要解决这些问题,可以将代码更新为如下所示的内容:
void intHashTable::remove(int num)
{
int location = ((unsigned)num) % size;
Node * runner = table[location];
if (runner != NULL) {
if (runner->num == num) {
delete runner;
table[location] = NULL;
} else {
while (runner->next != NULL) {
if (runner->next->num == num) {
Node *temp = runner->next;
runner->next = runner->next->next;
delete temp;
break;
}
runner = runner->next;
}
}
}
}
另请注意,我已经从 delete
中删除了括号,这是一个C++关键字而不是函数。
如果您使用双向链表(即使用前一个指针和下一个指针),那么您可以稍微简化此代码,尽管对于像哈希表这样只倾向于沿一个方向迭代的东西,它可能不值得花费额外的指针(在 64 位系统上每个项目额外 8 个字节)。
您没有更新循环中的temp
和runner
变量:
while(temp != NULL)
{
if(temp->num == num)
{
runner->next = temp->next;
delete temp;
break;
}
runner = temp; // Keep previous element to change its next pointer when num found
temp = temp->next; // Advance current pointer to next element
}
相关文章:
- 为什么我的删除节点函数实际上没有删除节点?
- 我们可以删除链表中静态内存中的节点吗
- 为什么"delete"关键字不删除节点?
- 为什么我的双向链表删除函数会删除多个节点?
- 编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限
- 删除 XML 文件中的子节点C++
- 创建了一个链表,但如何删除 c++ 中的"所有"节点
- 从unordered_map中删除单个节点
- 删除链表中的特定节点
- 在C++中删除双向链表的头节点后出现访问冲突异常
- 删除链表中的节点 - 分段错误
- 删除链接列表中剩余的最后一个节点
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- 使用函数引用指向节点的指针删除链表中的节点?
- 双向链表 - 无法删除第一个节点
- 双向链表 std::unique_ptr 类在节点删除时无法按预期工作
- BST 节点删除 - 指针未正确删除
- 节点删除功能的链表问题
- 布尔函数始终为真,单向链表中的尾节点删除创建无限循环
- AVL树中节点删除值异常