贴代码,上干货。
#include <iostream>
using namespace std;
#define HASHSIZE 15
#define NULLKEY -32768 //不可能的值
哈希表数据结构:
typedef struct
{
int *elem; //数组元素的基址,动态分配数据
int count; //当前数据元素的个数
}HashTable;
哈希表初始化:
int InitHashTable(HashTable *H)
{
H->count = HASHSIZE;
//H->elem = (int *)malloc(HASHSIZE * sizeof(int));
H->elem = new int[HASHSIZE];
if (!H->elem)
{
return -1;
}
for (int i = 0; i < HASHSIZE; i++)
{
H->elem[i] = NULLKEY;
}
return 0;
}
除留余数法求偏移地址:
//使用除留余数法
int Hash(int key)
{
return key % HASHSIZE;
}
哈希表插入操作:
//插入关键字到散列表
void InsertHash(HashTable *H, int key)
{
int addr;
addr = Hash(key); //偏移地址
while (H->elem[addr] != NULLKEY) //如果不为空,则产生冲突
{
addr = (addr + 1) % HASHSIZE; //采用开放定址法线性探测去找空位
}
H->elem[addr] = key;
}
哈希表查找操作:
//在散列表中查找关键字
int SearchHash(HashTable H, int key, int *addr)
{
*addr = Hash(key);
while (H.elem[*addr] != key)
{
*addr = (*addr + 1) % HASHSIZE;
if (H.elem[*addr] == NULLKEY || *addr == Hash(key))
{
return -1;
}
}
return 0;
}
主函数:
int main(int argc, char *argv[])
{
HashTable *H = new HashTable;
int key[] = { 123, 456, 7000, 8, 1, 13, 11, 555, 425, 393, 212, 546, 2, 99, 196 };
int i;
InitHashTable(H);
for (i = 0; i<HASHSIZE; i++)
{
InsertHash(H, key[i]);
}
for (i = 0; i<HASHSIZE; i++)
{
int address;
SearchHash(*H, key[i], &address);
cout << key[i] << " " << address << endl;
}
return 0;
}