从链表中删除节点

时间:2013-01-24 10:49:09

标签: c++ linked-list hashtable nodes

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

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

}

2 个答案:

答案 0 :(得分:2)

您尚未更新temp以指向循环中的下一个项目:

temp = temp->next;

您似乎也代表一个空行,表格中有一个NULL指针,但您在代码中没有正确处理这种情况 - 如果runnerNULL那么您当您尝试在第一次检查中访问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个字节)。

答案 1 :(得分: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
    }