Remove函数删除哈希表中的所有节点
Remove function removes all nodes in hash table
下面这段代码用于从哈希表中删除一个条目。当我运行代码时,程序不会崩溃,而是需要删除元素的特定桶中的所有节点都被删除了。插入和删除元素的计数正常。
示例删除之前。节点数= 11
Bucket[0]
Node01, Node02, Node03
Bucket[1]
Node11, Node12, Node13, Node14
Bucket[2]
Node21, Node22
Bucket[3]
EMPTY
Bucket[4]
Node41, Node42
删除Node12
哈希表变成。节点数= 10
Bucket[0]
Node01, Node02, Node03
Bucket[1]
EMPTY //This should be Node11, Node13, Node14
Bucket[2]
Node21, Node22
Bucket[3]
EMPTY
Bucket[4]
Node41, Node42
删除方法
void HashT::Remove(string key)
{
size_t index = HashFunc(key);
if (table[index] != NULL)
{
node* prev = NULL;
node* curr = table[index];
while (curr->next != NULL && entry->item.GetKey() != key)
{
prev = curr;
curr = curr->next;
}
if (curr->item.GetKey() == key)
{
node* nextEntry = curr->next;
table[index] = nextEntry;
delete entry;
size--;
cout << "Removedn";
}
}
}
我使用这个函数插入到哈希表
void HashT::Ins(Data& data)
{
size_t index = HashFunc(data.GetKey());
node * newData = new node(data);
if(table[index] != NULL && table[index]->item.GetKey() == data.GetKey())
cout << "Do nothingn";
else
newData->next = table[index];
table[index] = newData;
size++;
}
在main()中调用Remove
看起来像这样
HashT ht(cout);
ht.Ins(Data(node1));
ht.Ins(Data(node2));
ht.Ins(Data(node3));
ht.Ins(Data(node4));
ht.Remove("string3"); //This does not work
ht.Ins(Data(node5));
ht.Ins(Data(node6));
ht.Ins(Data(node7));
ht.Ins(Data(node8));
ht.Remove("string2"); //This Works
ht.Remove("string5"); //This doesnt work
我建议如下修改:
void HashT::Remove(string key)
{
size_t index = HashFunc(key);
if (table[index] != NULL)
{
node* prev = NULL;
node* curr = table[index];
while (curr->next != NULL && entry->item.GetKey() != key)
{
prev = curr;
curr = curr->next;
}
if (curr->item.GetKey() == key) // change (1) !!!!
{
node* nextEntry = curr->next;
if (prev) // change 2 !!!!
prev->next = nextEntry; // change 2 !!!!
else table[index] = nextEntry; // change 2 !!!
delete entry;
size--;
cout << "Removedn";
}
else if (curr->next!=NULL) // change 1 !!!
cout << "Not found in bucketn"; // change 1 !!!
}
}
change 2:只有当发现的元素是桶中的第一个元素时,才更新表[index]。在所有其他情况下,这是经典的元素删除,您将前一个元素的下一个指针更改为下一个元素(经典链表更新)。
编辑:我以前的更改1被初始entry
误导,对不起。我已经对它进行了更新,以明确在bucket中找不到项的情况。
相关文章:
- 为什么我的删除节点函数实际上没有删除节点?
- 为什么我们要为avl树实现返回一个指向节点的指针,而不是void函数
- 为什么我的双向链表删除函数会删除多个节点?
- 编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限
- 为什么提升图库的 read_graphviz() 函数会改变节点的索引
- C++二叉搜索树模板从函数返回节点
- 类成员函数无法访问同一类的私有结构节点?
- 节点插件 API 将数组作为函数参数传递
- 修改链表主函数代码,用户将在其中输入节点的索引和数据以及正确的消息
- 使用函数引用指向节点的指针删除链表中的节点?
- 函数无法识别我在C++传递节点指针向量?
- 为什么将函数的返回类型从结构节点*更改为void后,链表的元素没有显示create_ll和显示?
- 简单树插入节点函数显示为空
- 正在处理约瑟夫斯问题,节点函数不起作用
- 查找二叉树的父节点函数
- TinyXML2:替换节点函数
- C++ 链表 - 插入节点函数不会更新函数范围之外的值
- C++ largest_free节点函数段错误链表
- 删除链表中的节点函数
- 递归查找节点函数