HashTable的双重散列表

本文介绍了一种改进的散列表实现方法——双散列法,通过使用两个散列函数来解决散列冲突问题,提高了查找效率。文章提供了完整的C++实现代码,包括散列表的初始化、插入、查找等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思想:
添加额外的散列函数计算搜索命中的增量,即将线性探测时的+1(逐个后移检测);改为平移Hash2的值。

#include <iostream>
#include <stdlib.h>
#define GetKey(A) ( (A - 'A')%100 )
#define Hash(v, M) (v % M) 
#define Hash2(v, M) (v % 5 + 1)
#define eq(A, B) (A == B)
#define NULLItem '\0'
#define MAX 20;//最大元素个数
typedef char Item;
typedef int KeyItem; //关键值类型

using namespace std;

static int M, N; //M:hash-size; N:element numbers
static Item* hash_table;

void HashTableInit(int max)
{
    N = 0;
    M = 2*max;
    hash_table = new Item[M];
    for(int i = 0; i < M; i++)
        hash_table[i] = NULLItem;
}
void HashTableInsert(Item item)
{
    int hash_key = Hash(GetKey(item), M);
    int hash_key2 = Hash2(GetKey(item), M);

    while (hash_table[hash_key] != NULLItem) {
        // hash_key = (hash_key+1) % M; 线性探测时 +1
        hash_key = (hash_key+hash_key2) % M;
    }
    hash_table[hash_key] = item;
    N++;
}

Item HashTabelSearch(KeyItem v)
{
    int hash_key = Hash(v, M);
    int hash_key2 = Hash2(v, M);
    while (hash_table[hash_key] != NULLItem) {
        if(eq(GetKey(hash_table[hash_key]), v))
            break;
        hash_key = (hash_key+hash_key2) % M;
    }
    return hash_table[hash_key];
}

void HashTabelPrint()
{
    cout << endl << "Print Hash Table: " << endl;
    for(int i = 0; i < M; i++)
        cout << i << "-" << hash_table[i] << "   ";
    cout << endl;
}
int main()
{
    int max = MAX;
    HashTableInit(max);
    cout << "Item - Key - Hash_Key:"<< endl;
    for (int i = 0; i < max; i++) {
        Item item = 'A' + rand()%26;
        cout << item << "-" << GetKey(item) << "-" <<Hash(GetKey(item), M) << ";   ";
        HashTableInsert(item);
    }
    cout << endl;
    HashTabelPrint();
    Item item = 'G';
    KeyItem k = 8;
    cout << endl;
    cout << "Search key=" << k << ": " << HashTabelSearch(k) << endl;
    cout << "Delete item=" << item << ": " <<endl;
    // HashTabelDelete(item);
    HashTabelPrint();

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值