4

我创建了一个哈希表,我想从链表中删除一个节点。该代码适用于删除第一个节点,但不适用于删除其他节点。

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;
            }
        }
    }
}

}

4

2 回答 2

2

您尚未更新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 个字节)。

于 2013-01-24T10:53:00.910 回答
1

您没有更新temprunner循环内的变量:

    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
    }
于 2013-01-24T11:01:20.733 回答