在具有开放寻址的哈希表中插入节点 [优化逻辑]
Inserting node in Hash table with open addressing [Optimizing the logic]
我正在尝试理解具有开放寻址的数据结构,哈希表。
我目前正在阅读 geekforgeeks 提供的源代码,但我对代码有几个问题。
下面是来自极客锻inserting Node
的粘贴功能。
//Function to add key value pair
void insertNode(K key, V value)
{
HashNode<K,V> *temp = new HashNode<K,V>(key, value);
// Apply hash function to find index for given key
int hashIndex = hashCode(key);
//find next free space
while(arr[hashIndex] != NULL && arr[hashIndex]->key != key //// LINE 9 //////
&& arr[hashIndex]->key != -1)
{
hashIndex++;
hashIndex %= capacity;
}
//if new node to be inserted increase the current size
if(arr[hashIndex] == NULL || arr[hashIndex]->key == -1) //// LINE 17 //////
size++;
arr[hashIndex] = temp;
}
问题
在第 9 行中,为什么要检查三个条件,即,
- 如果
slot inside the hash table is null
===>arr[hashIndex] != NULL
- 如果
slot has the same key with the node that is going to be inserted
===>arr[hashIndex]->key != key
- 如果
slot has the key of -1, which indicates the slot where node was deleted before
===>arr[hashIndex]->key != -1
如果我要优化这段代码,我相信检查slot is NULL or not
是否已经足够了。
- 如果
在第 17 行中,为什么要在将节点分配给插槽之前递增 HashMap 的大小属性? ===>
if(arr[hashIndex] == NULL || arr[hashIndex]->key == -1) size++;
对我来说,这个逻辑似乎很混乱。
我宁愿做,arr[hashIndex] = temp; size++;
假设极客的逻辑写得很好,你能向我解释一下why the logic for inserting the new node to a hash table with open addressing
具体针对我提出的两点实现的吗?
具有有效索引的三个条件是:
- 索引处的对象为 NULL
- 或者对象不是 NULL,但它的键与我们插入的键相同
- 或者对象不为 NULL,但其键值为
-1
由于所有三个条件都发生了否定,因此我们没有有效的索引,并且循环继续滚动。
在第 17 行中:仅当插入不重用现有索引时,大小才会递增,因此节点new
(这意味着条件 1 或 3 适用(。
相关文章:
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- 将二叉树的节点插入链表 (C++)
- 如何在使用 ItemType 的模板类时将新节点插入二叉树 c++.(我是 c++ 的新手)
- 单个链表,节点插入最低到最高节点值的问题
- 无法将节点插入C 中的链接列表中
- 将节点插入链表只会转到开头或结尾
- 将节点插入 BST
- 按排序顺序将节点插入链表
- LinkedList节点插入
- 二进制搜索树节点插入
- 使用级别顺序遍历将节点插入二叉树
- 尝试将节点插入链表中,但我需要一个重载运算符<函数
- 将节点插入二叉搜索树
- 尝试将节点插入矢量<node>,但程序在push_back时不断崩溃
- 将节点插入二进制搜索树/链表
- 将节点插入到不带头指针的排序列表中
- 错误:SList.cpp:(.text+0x69):尝试将节点插入链表头C++时未定义对"SLNode::SLNode()"的引用
- 为什么在尝试将新节点插入列表时出错
- 节点插入二进制树C++
- 为什么我不能将 head 之后的节点插入C++链表?