在具有开放寻址的哈希表中插入节点 [优化逻辑]

Inserting node in Hash table with open addressing [Optimizing the logic]

本文关键字:节点 插入 优化 哈希表 寻址      更新时间:2023-10-16

我正在尝试理解具有开放寻址的数据结构,哈希表。
我目前正在阅读 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; 
} 

问题

  1. 在第 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是否已经足够了。
  2. 在第 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具体针对我提出的两点实现的吗?

具有有效索引的三个条件是:

  1. 索引处的对象为 NULL
  2. 或者对象不是 NULL,但它的键与我们插入的键相同
  3. 或者对象不为 NULL,但其键值为-1

由于所有三个条件都发生了否定,因此我们没有有效的索引,并且循环继续滚动。

在第 17 行中:仅当插入不重用现有索引时,大小才会递增,因此节点new(这意味着条件 1 或 3 适用(。