代码学习自《大话数据结构》
#include<iostream>
using namespace std;
//散列表
#define SUCCESS 1
#define UNSUCCESS 0
#define HASHSIZE 12
#define NULLKEY -32768
struct HashTable
{
int* elem;
int count;
};
int m = 0;//散列表表长
bool initHashTable(HashTable*);//哈希表的初始化
int Hash(int);//散列函数,获得对应下标
void insertHash(HashTable*, int);//向哈希表插入数值
bool Hash_search(HashTable*, int ,int *);//散列表查找
int main()
{}
bool initHashTable(HashTable* h)//哈希表的初始化
{
h->count=m = HASHSIZE;
h->elem = new int[m];//记得赋内存
for(int i=0;i<m;++i)
{
h->elem[i] = NULLKEY;
}
return true;
}
int Hash(int key)//散列函数,获得对应下标,除留余数法
{
return key % m;
}
void insertHash(HashTable* h, int key)//向哈希表插入数值
{
int addr = Hash(key);
while(h->elem[addr]!=NULLKEY)
{
addr = Hash(addr + 1);
}
h->elem[addr] = key;
}
bool Hash_search(HashTable* h, int key, int* addr)//散列表查找
{
*addr = Hash(key);
while(h->elem[*addr]!=key)
{
*addr = Hash(*addr + 1);
if(h->elem[*addr] == NULLKEY ||*addr==Hash(key))//不存在该关键字
{
return UNSUCCESS;
}
}
return SUCCESS
}