哈希表与合并哈希

时间:2015-09-10 02:24:57

标签: java hashtable hash-collision

我试图弄清楚如何将使用二次探测实现的哈希表类的add方法转换为使用合并哈希的碰撞解决方法。我知道它与链表有关,但因为我是哈希表的新手,我不知道从哪里开始。

这是有问题的添加方法,

public boolean add(AnyType x) {
    int currentPos = findPos(x);
    if (isActive(array, currentPos))
        return false;
    if (array[currentPos] == null)
        occupied++;
    array[currentPos] = new HashEntry(x, true);
    currentSize++;
    modCount++;
    if (occupied > array.length / 2)
        rehash();
    return true;
}

如果有人能告诉我如何将此方法转换为使用合并散列,我将非常感激。

1 个答案:

答案 0 :(得分:0)

因此,在我遵循维基百科指南和代码here后,我将代码修改为以下内容。我用评论解释每个部分。

public boolean add(AnyType x) {
    // Finds the place that you want to insert into your table.
    // I believe the function contains the hash mapping
    int currentPos = findPos(x);
    // if the place is empty, you will insert your hash in there
    if (array[currentPos] == null) {
        array[currentPos] = new HashEntry(x, true);
    } else {
        // The place has been occupied (collision occured), so we will 
        // add it as a second item like a link list.
        // But, we do not want to allocate a new space and we use the 
        // empty spaces we have in our hash table instead.
        // That is the differece between coalesced hash and speparate chaining

        // the indexes are from 0 to HASH_TABLE_SIZE -1
        int cursor = HASH_TABLE_SIZE - 1; 
        /* Find the first empty bucket for the new entry */
        while ( cursor >= 0 && array[cursor] != NULL )
            --cursor;

        /* The table is full, terminate unsuccessfully */
        if ( cursor == -1 )
          return false;

        // Initial your new value in an empty bucket we found in the table
        array[cursor] = new HashEntry(x, true);

        /* Find the last node in the chain and point to it */
        // Here we need to find the tail of the link list in our hash table
        // We do not want to miss the link list that we made from the past,
        // therefore, we need to do the following
        struct node* it = array[currentPos];
        while ( it->next != NULL )
          it = it->next;
        // Now we assign the 
        it->next = array[cursor];       
    }
    return true;
}

我希望它有所帮助。