从链表中删除节点

Removing a node from a linked-list

本文关键字:节点 删除 链表      更新时间:2023-10-16

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

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 个字节)。

您没有更新循环中的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
    }