我创建了一个哈希表,并且想从链表中删除一个节点。该代码适用于删除第一个节点,但不适用于删除其他节点。
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 个字节)。
关于c++ - 从链表中删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14499508/